【问题标题】:Background colour of table row using jQuery使用jQuery的表格行的背景颜色
【发布时间】:2015-05-26 11:03:16
【问题描述】:

我有一个简单的表格,当用户悬停行元素时,我使用 jQuery 更改行颜色。

$('tr').on('mouseenter', function(){
    $(this).css({background:'#f00'});
});
$('tr').on('mouseout', function(){
    $(this).css({background:''});
});

当用户将鼠标从 A 列移动到 B 列(在同一行)时,会触发 mouseout 事件。

jsFiddle here.

测试用例:将鼠标移到包含“Foo”的单元格上。将鼠标向右移动到带有“Bar”的单元格。该行应保持红色,但不会。

在 IE11 和 Chrome 42.0.2311.152m 中测试。由于我实际使用的选择器,CSS 不合适。 (附上minimal complete verifiable example)。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你可以只使用 CSS 来处理样式:

    tr:hover {
        background-color:#f00;
    }
    

    jsFiddle here

    【讨论】:

    • CSS 不合适 - 我在现实中使用更复杂的选择器。已编辑,谢谢。
    【解决方案2】:

    你可以更好地使用 hover

    $('tr').hover(function () {
        $(this).css({background:'#f00' });
    }, function () {
         $(this).css({background:'' });
    });
    

    DEMO

    【讨论】:

      【解决方案3】:

      当鼠标指针离开任何子节点时触发 mouseout 事件 元素以及选定的元素。

      mouseleave 事件仅在鼠标指针离开时触发 被选中的元素。

      使用mouseleave 事件而不是mouseout

      $('tr').on('mouseenter', function(){
          $(this).css({background:'#f00'});
      });
      $('tr').on('mouseleave', function(){
          $(this).css({background:''});
      });
      

      【讨论】:

        【解决方案4】:

        解决方法: 将mouseenter/mouseout 事件应用于td,然后改用$(this).parent().css({background:...});

        jsFiddle here.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-16
          • 1970-01-01
          • 2012-10-06
          • 1970-01-01
          • 2012-05-31
          • 2020-03-13
          • 2016-11-13
          • 2015-08-05
          相关资源
          最近更新 更多