2013-03-19 62 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