[英]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()
的方法,但这似乎绑定了事件mouseenter
和mouseleave
(我应该使用那些事件而不是mouseover
和mouseout
吗?)
You can user jQuery's hover()
method. 您可以使用jQuery的
hover()
方法。
Check out the sample and this jsFiddle Demonstration 看看样本和这个jsFiddle演示
$(elem).hover(function(ev) {
$(this).addClass('hover');
}, function(ev) {
$(this).removeClass('hover');
});
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.