有没有办法让这两者一起工作,还是我必须尝试使用 mouseenter 和 mouseleave?
最佳答案
您可以将 event.stopPropagation()
与 .hover()
一起使用,但您实际上还是将 mouseenter
和 mouseleave
与 .hover()
一起使用。如果您向 .hover()
提供 1 个函数,它会在两个事件上运行,如果您提供 2 个函数,第一个是 mouseenter
处理程序,第二个是 mouseleave
处理程序。
但是,这可能不是您想要的...因为 mouseenter
不会触发当进入一个 child 时,这实际上就是它存在的具体原因,mouseout
将进入 child 时开火。 You can see that's there's no difference in a demo here ,从上到下悬停,对 .stopPropagation()
进行注释和取消注释,这没有区别...因为事件不会冒泡到父级。
但是,如果您使用的是 mouseover
和 mouseout
,那么就很重要了,如下所示:
$("li").mouseover(function(e) {
$(this).addClass("red").parents().removeClass("red");
}).mouseout(function(e) {
$(this).removeClass("red");
});
现在我们有一个冒泡问题,因为事件冒泡了,将类添加到我们刚从中删除它的父类,see a demo of the problem here。但是,如果我们用 .stopPropagation()
停止那个气泡,我们会得到想要的效果,如下所示:
$("li").mouseover(function(e) {
$(this).addClass("red").parents().removeClass("red");
e.stopPropagation();
}).mouseout(function(e) {
$(this).removeClass("red");
});
You can see in this demo how this works differently 。
简而言之:是 event.stopPropagation()
与 .hover()
一起使用,但很可能正是您所追求的。
关于javascript - e.stopPropagation() 和 jQuery.hover(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947178/