【问题标题】:Change table row color on hover (jQuery or CSS)悬停时更改表格行颜色(jQuery 或 CSS)
【发布时间】:2014-10-28 19:37:38
【问题描述】:

我的问题是我的表格中已经有一些“突出显示”(意味着他们有自己的背景颜色来突出显示它们)单元格,当我使用代码更改整个颜色时,这些单元格不会改变它们的背景颜色鼠标悬停在它们上方时的行。

悬停在一行上只会更改未突出显示的单元格的背景颜色。

如何解决这个问题,使整行更改背景颜色?

我有这个 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>

【问题讨论】:

  • 为什么不 #infotable tr:hover { background: #color }
  • @RemySheppard 这只是为了测试,但谢谢 :)

标签: javascript jquery html css


【解决方案1】:

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

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

Example fiddle

【讨论】:

  • 无论如何都比我的小提琴好:P
  • 这是最好的方法。不要忘记提及某些 IE 版本需要特定的 behavior 文件,因此它适用于这些版本。
  • @CassieKasandr 没问题,很乐意提供帮助。
【解决方案2】:

仅通过更改 javascript 将类悬停添加到所有 tdtr

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

FIDDLE

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      在 css 中试试这个

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

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多