如何一次检测两个元素上的mouseleave()?

答案可以是vanilla js或jQuery。 如果用户不再hover在ID为“myLink”的链接或ID为“mySpan”的跨度上,我想隐藏ID为“myDiv”的div。 如果用户将鼠标hover在任一元素上,“myDiv”仍将显示,但第二个用户不会将鼠标hover在两者中的任何一个上(无论用户的鼠标首先离开哪个元素)“myDiv”将从脸部消失存在

换句话说,这是我在一个元素上检测鼠标离开的方式:

$('#someElement').mouseleave(function() { // do something }); 

但怎么说(以某种方式实际工作):

 $('#someElement').mouseleave() || $('#someOtherElement').mouseleave()) { // do something }); 

怎么检测到这个?

您可以使用多重选择器 :

 $("#someElement, #someOtherElement").mouseleave(function() { // Do something. }); 

像这样的东西应该工作:

 var count = 0; $('#myLink, #mySpan').mouseenter(function(){ count++; $('#myDiv').show(); }).mouseleave(function(){ count--; if (!count) { $('#myDiv').hide(); } }); 

的jsfiddle

虽然lonesomeday的答案是完全有效的,但我改变了我的html,将两个元素放在一个容器中。 我本来想避免这种情况,因此我不得不在其他html模板中为我的客户做更多的重构,但我认为它会在长期内付出代价。

 
Foo
Bar
$('#my-container').mouseleave(function() { console.log("left"); });

我想,这是你的解决方案!

 $(document).ready(function() { var someOtherElement = ""; $("#someElement").hover(function(){ var someOtherElement = $(this).attr("href"); $(someOtherElement).show(); }); $("#someElement").mouseleave(function(){ var someOtherElement= $(this).attr("href"); $(someOtherElement).mouseenter(function(){ $(someOtherElement).show(); }); $(someOtherElement).mouseleave(function(){ $(someOtherElement).hide(); }); }); }); ---- html ----    

你可以精美地使用setTimeout()来给mouseleave()函数一些“容差”,这意味着如果你离开div但在给定的时间内重新输入其中一个,它就不会触发hide()函数。

这是代码(添加到lonesomeday的答案):

 var count = 0; var tolerance = 500; $('#d1, #d2').mouseenter(function(){ count++; $('#d3').show(); }).mouseleave(function(){ count--; setTimeout(function () { if (!count) { $('#d3').hide(); } }, tolerance); }); 

http://jsfiddle.net/pFTfm/195/