悬停时更改表格行的颜色(jQuery或CSS)

Change table row color on hover (jQuery or CSS)

本文关键字:jQuery CSS 颜色 表格 悬停      更新时间:2023-09-26

我的问题是,我的表中已经有一些"高亮显示"的单元格(意味着它们有自己的背景色来高亮显示),当我使用代码在鼠标悬停时更改整行的颜色时,这些单元格不会更改其背景色。

覆盖一行只会更改未高亮显示的单元格的背景色。

如何修复此问题,使整行更改背景色?

我有这个HTML表格:

$(window).load(function() {
  $('#infotable tr').hover(function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
});
#infotable td { 
  padding:0.7em;
  border:#969696 1px solid;
}
.highlight {
  background:#DAFFD6;
}
.hover {
  background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody id="infotable">
    <tr>
      <td>Row #1</td>
      <td>889 kg</td>
      <td class="highlight">151 kg</td>
      <td>192 kg</td>
    </tr>
    <tr>
      <td>Row #2</td>
      <td>784 kg</td>
      <td>15 kg</td>
      <td class="highlight">64 kg</td>
    </tr>
  </tbody>
</table>

您可以单独在CSS中实现这一点。您只需要使:hover规则比td.highlight规则更具体。试试这个:

#infotable tr:hover td,
#infotable tr:hover td.highlight
{
    background:yellow;
}

小提琴示例

只需更改javascript,即可将类悬停添加到所有td而不是tr

  $('#infotable tr').hover(function()
  {
    $(this).find('td').addClass('hover');
  }, function()
  {
    $(this).find('td').removeClass('hover');
  });

FIDDLE

只需继承悬停检查此Fiddle 的样式

.hover, .hover .highlight
{
    background:yellow;
}

在css 中尝试此操作

#infotable tr td:hover
{
    background:yellow;
}