如何在jQuery中忽略子元素上的鼠标事件?

我有一个无序列表,其中包含附加到li元素的mouseover和mouseout事件。 每个都包含一个链接,并在li中有一些填充。 当鼠标hover在li上时,鼠标hover事件被触发,但当我鼠标hover在li中包含的链接时,mouseout和mouseover事件都按顺序触发。 似乎子元素正在触发它们的父元素鼠标事件……我该如何停止这个? 我希望它只是在鼠标hover在链接上时保持鼠标hover,而不是每次鼠标hover在链接上时都不激活动画。 这是我的代码;

jQuery(document).ready(function(){ jQuery('#menu li ul').hide(); jQuery('#menu li').mouseover( function() { jQuery(this).children("ul").show('fast').stop; return false; }); jQuery('#menu li').mouseout( function() { jQuery(this).children("ul").hide('fast').stop; return false; }); });  

我似乎找到了自己问题的答案。 对于任何可能遇到同样问题的人; 请尝试使用此代码。 似乎hover不像其他鼠标事件那样冒泡到子元素中。

 jQuery('#menu li').hover( function() { jQuery(this).children('ul').show('fast'); return false; }, function() { jQuery(this).children('ul').hide('fast'); return false; } ); 

使用“ event.stopPropagation ()”来阻止事件向上冒泡:

  jQuery('#menu li a').mouseover( function(evt) { evt.stopPropagation(); return false; }); jQuery('#menu li a').mouseout( function(evt) { evt.stopPropagation(); return false; }); 

或者使用mouseentermouseleave事件而不是mouseover / out。 jQuery规范了他们在浏览器中的行为,这些事件的好处是没有冒泡……

我在寻找JS中的equivelant行为,你可以在AS3中放置:

 object.mouseenabled = false; 

我发现效果很好的方法是使用CSS并放置:

 .element { pointer-events: none; } 

(但我想这只有在你根本不需要任何元素的情况下才有效。我将它用于hover时弹出的工具提示,但是当你将鼠标移开时不要让它变得怪异)。

你可以试试这个

 $('#menu li').live('mouseenter mouseleave', function (e) { if (e.type == 'mouseenter') { //Show ul } else { //Hide ul } }); 

优点是使用事件委托。 祝好运!

使用css类来区分不同的菜单级别。 然后,您可以在jQuery选择器中轻松搜索一个类或另一个类。