简体   繁体   English

在jQuery中,什么是在mouseover上添加类并在mouseout上删除它的最佳方法?

[英]In jQuery what's the best way to add a class on mouseover and remove it on mouseout?

Is there a jQuery shortcut for this? 这有jQuery快捷方式吗?

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

I see in the jQuery docs a method called hover() , but that seems to bind on events mouseenter and mouseleave (should I be using those events instead of mouseover and mouseout ?) 我在jQuery文档中看到了一个名为hover()的方法,但这似乎绑定了事件mouseentermouseleave (我应该使用那些事件而不是mouseovermouseout吗?)

Description 描述

You can user jQuery's hover() method. 您可以使用jQuery的hover()方法。

Check out the sample and this jsFiddle Demonstration 看看样本和这个jsFiddle演示

Sample 样品

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

More Information 更多信息

The simplest way, to remove duplication of code, is by passing one argument to hover and use toggleClass : 删除代码重复的最简单方法是将一个参数传递给hover并使用toggleClass

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

Or: 要么:

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

hover() is only a bit more compact: hover()只是更紧凑:

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

For the difference between mouseover/mouseout and mouseenter/mouseleave, see What is the difference between the mouseover and mouseenter events? 有关mouseover / mouseout和mouseenter / mouseleave 之间的区别 ,请参阅mouseover和mouseenter事件之间的区别是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM