【问题标题】:In jQuery what's the best way to add a class on mouseover and remove it on mouseout?在jQuery中,在鼠标悬停时添加类并在鼠标悬停时将其删除的最佳方法是什么?
【发布时间】:2012-02-09 03:35:16
【问题描述】:

这个有 jQuery 快捷方式吗?

$(element).on("mouseover", function() {
    $(this).addClass("hover");
}).on("mouseout", function() {
    $(this).removeClass("hover");
});

我在 jQuery 文档中看到了一个名为 hover() 的方法,但这似乎与事件 mouseentermouseleave 绑定(我应该使用这些事件而不是 mouseovermouseout 吗?)

【问题讨论】:

    标签: javascript jquery hover mouseover mouseout


    【解决方案1】:

    说明

    您可以使用 jQuery 的 hover() 方法。

    查看示例和此jsFiddle Demonstration

    样本

    $(elem).hover(function(ev) {
        $(this).addClass('hover');
    }, function(ev) {
        $(this).removeClass('hover');
    });
    

    更多信息

    【讨论】:

    • 有什么理由不使用@lonesomeday 的更紧凑的表单吗?
    • (假设我知道初始状态没有“悬停”类)
    • 是的,你说得对。 lonesomeday's的示例只是切换班级,无论你是否设置了班级初始。
    • 好的。 @lonesomeday 的回答非常巧妙,可能对我有用,但我会选择更安全的路线。
    • 很高兴为您提供帮助!祝你有美好的一天!
    【解决方案2】:

    删除重复代码的最简单方法是将一个参数传递给hover 并使用toggleClass

    $(elem).hover(function() {
        $(this).toggleClass('hover');
    });
    

    【讨论】:

    • 这肯定总是有效吗? “切换状态”有什么办法不同步吗?
    • 您冒险,因为您不知道初始状态是什么。
    • @BenLee 仅当您使用其他一些代码进行切换时,这似乎不太可能/愚蠢。
    • @gdoron,假设我知道初始状态。我只是想确保没有边缘情况(比如光标从“元素上方”到“浏览器窗口外”再到“不超过元素”类型的交易)。
    • 我投票支持这个和 dknaack 的答案——是的,如果您不知道或无法控制您的完整场景,切换状态可能会不同步。但如果你是,它非常光滑。但另一方面,3 行与 5 行......你总是可以选择 dknaack 的安全路线。
    【解决方案3】:

    或者:

    $(element).hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover");
    });
    

    【讨论】:

      【解决方案4】:

      hover() 只是更紧凑一点:

      $(elem).hover(function(ev) {
          $(this).addClass('hover');
      },function(ev) {
          $(this).removeClass('hover');
      });
      

      mouseover/mouseout 和 mouseenter/mouseleave 的区别,见What is the difference between the mouseover and mouseenter events?

      【讨论】:

        猜你喜欢
        • 2012-05-04
        • 2011-04-14
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2015-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多