e.stopPropagation()和jQuery.hover() [英] e.stopPropagation() and jQuery.hover()
问题描述
有没有办法让这两个一起工作或者我必须尝试使用mouseenter和mouseleave?
Is there a way to have both of these work together or do I have to try using the mouseenter and mouseleave instead?
推荐答案
您可以使用 event.stopPropagation()
使用 .hover()
,但你实际使用 mouseenter
和 mouseleave
无论如何,a href =http://api.jquery.com/hover/ =noreferrer> .hover()
。如果你为 .hover()
提供1个函数,它会在两个事件上运行,如果你提供2个函数,第一个是 mouseenter
handler,第二个是 mouseleave
处理程序。
You can use event.stopPropagation()
with .hover()
, but you're actually using mouseenter
and mouseleave
with .hover()
anyway. If you provide 1 function to .hover()
, it runs on both events, if you provide 2 functions, the first is the mouseenter
handler, the second is the mouseleave
handler.
但是,这可能不是你的'之后......因为 mouseenter
在输入孩子时不会触发,这实际上是它存在的具体原因, mouseout
将在进入孩子时开火。 您可以看到这里的演示没有区别,从上到下悬停,评论并取消注释 .stopPropagation()
,它没有区别......因为事件没有冒泡到父母。
However, this may not be what you're after...since mouseenter
doesn't fire when entering a child, that's actually specifically why it exists, mouseout
will fire when entering a child. You can see that's there's no difference in a demo here, hover from top to bottom, comment and uncomment out the .stopPropagation()
, it makes no difference...because the event doesn't bubble to the parent.
但是,如果您使用的是 mouseover
并且 mouseout
,然后它这很重要:
However if you are using mouseover
and mouseout
, then it would matter, like this:
$("li").mouseover(function(e) {
$(this).addClass("red").parents().removeClass("red");
}).mouseout(function(e) {
$(this).removeClass("red");
});
现在我们有一个冒泡问题,因为事件冒出来,将类添加到我们刚删除的父级,查看演示问题在这里。但是,如果我们使用 .stopPropagation 停止该气泡()
,我们得到了预期的效果,如下所示:
Now we have a bubbling problem, because the event bubbles right up, adding the class to the parent we just removed it from, see a demo of the problem here. However if we stop that bubble, with the .stopPropagation()
, we get the desired effect, like this:
$("li").mouseover(function(e) {
$(this).addClass("red").parents().removeClass("red");
e.stopPropagation();
}).mouseout(function(e) {
$(this).removeClass("red");
});
简而言之:是 event.stopPropagation()
适用于 .hover()
,但很可能,
这篇关于e.stopPropagation()和jQuery.hover()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!