2013-03-19 107 views
3

所有,我坚持处理嵌套元素悬停处理程序的问题。看来当鼠标输入child时,祖先也处于hover状态,有没有什么办法触发hoverout事件的祖先,当鼠标输入child元素时?嵌套元素悬停句柄

下面是我试图做到目前为止。请检查它。

<style> 
div 
{ 
    border:1px solid red; 
    margin:10px; 
    padding:10px; 
} 
</style> 


    <script> 
     $(function() { 
      $('div').each(function(){ 
      var current = this; 
      $(this).hover(function(event){ 
       event.stopPropagation();// doesn't work. 
       console.log('Capture for hover in ' + current.tagName + '#'+ current.id + 
        ' target is ' + event.target.id); }, 
       function(event){ 
        event.stopPropagation(); 
        console.log('Capture for hover out' + current.tagName + '#'+ current.id + 
        ' target is ' + event.target.id); }); 

          }); 
         }); 
</script> 

<body id="greatgrandpa">       
     <div id="grandpa"> 
       <div id="parent"> 
        <div id="child"/> 
       </div> 
     </div> 
</body> 
+0

只需删除asterix并运行图像上的功能?您将循环中的事件处理程序附加到遍历页面上所有元素的循环中! – adeneo 2013-03-19 03:22:17

+0

嗨,@ adeneo,我只是将问题更新清楚。请检查它。谢谢。 – 2013-03-19 03:30:40

+0

我真的不明白,但是你可以将mouseenter/leave函数设置为任何你喜欢的东西,比如[** FIDDLE **](http://jsfiddle.net/FXU65/)?? – adeneo 2013-03-19 03:37:42

回答

3

.hover()方法结合处理程序既mouseentermouseleave事件。您可以使用它在鼠标位于元素内时简单地将行为应用于元素。

但是,如果您使用mouseovermouseout事件,则当鼠标移入和移出元素及其后代时触发这些事件。

请参阅http://jsfiddle.net/5yQY5/您的示例的替代尝试。

+0

它让我感到困惑,然后才得到你的答案。谢谢, – 2013-03-19 04:01:53

1

使用鼠标悬停和鼠标移开事件,而不是

$(function() { 
    $('div').on('mouseover', function(e){ 
     e.stopPropagation(); 
     $(this).addClass('my-bg'); 
    }).on('mouseout', function(e){ 
     $(this).removeClass('my-bg'); 
    }) 
}); 

演示:Fiddle

注:无需通过每个格迭代,然后添加事件处理程序为他们每个人,你可以拨打$('div').hover(...),它将寄存器hover所有div的处理程序

+0

嗨,@阿兰P Johny,你能告诉我'hoverin hoverout'和'mouseover mouseout'之间的区别吗?谢谢。 – 2013-03-19 03:57:30

+0

你可以看看这篇文章http://stackoverflow.com/questions/1104344/what-is-the-difference-between-the-mouseover-and-mouseenter-events – 2013-03-19 04:07:23

1

您需要查找目标是否DOM是否为child

$(this).hover(function(e){ 
    if($(e.target).is('div#child')) 
    { 
     // your child span is being hovered over 
     e.stopPropagation(); 
    } 
    else if($(e.target).is('div#parent')) 
    { 
     // your parent element is being hovered over 
    } 
}); 
+0

嗨,朋友,阿伦P Johny的回答是最好的方法。谢谢。 – 2013-03-19 03:51:22

+0

@ Joe.wang总是欢迎...我只是试图根据你的代码来回答,所以我想为什么编辑代码给出了适合当前代码的解决方案.. – 2013-03-19 03:54:56