2012-04-22 105 views
1

我需要在鼠標懸停時顯示圖像的工具提示。我爲此寫了下面的代碼。我當前的問題是,當我將圖像放入工具提示div中時,事件只發生在圖像元素上。我怎麼能忽略我父母的工具提示div的子元素的mouseover和mouseout事件?忽略Mouseover元素的Mouseout事件

$("document").ready(function() { 
     $('.tooltip').mouseover(function(e){ 
      var id = $(this).siblings('.tooltip-c').attr('id'); 
      $('.tp'+id).fadeIn(500); 
      $('.tp'+id).mouseout(function(event){ 
       $('.tp'+id).fadeOut(300); 
      }); 
     }); 
    }); 

請幫幫我吧。我很無奈。

+0

有什麼問題嗎? – mihai 2012-04-22 09:15:58

+0

如何忽略Mouseover元素的Mouseout事件? – 2012-04-22 09:20:25

+0

哪個孩子?目前的答案是無法回答的。 – gdoron 2012-04-22 09:23:31

回答

2

您可以在事件處理函數中使用事件.stopPropagation()方法。

$("document").ready(function() { 
    $('.tooltip').mouseenter(function(event){ 
     var id = $(this).siblings('.tooltip-c').attr('id'); 
     $('.tp'+id).fadeIn(500); 
     event.stopPropagation(); 
    }); 
}); 
+0

還是老兄... – 2012-04-22 09:39:58

+0

@Gihan Dilusha在你的事件處理函數參數中傳遞'e'或'event',然後使用'.stopPropagation'作爲它的方法。我甚至使用了 – undefined 2012-04-22 09:42:27

+0

。但它是一樣的:( – 2012-04-22 10:37:27

17

嘗試使用.mouseenter().mouseleave()代替。他們處理與.mouseover().mouseout()不同的事件冒泡。我認爲它應該可以解決你的問題:

$("document").ready(function() { 
    $('.tooltip').mouseenter(function(e){ 
    var id = $(this).siblings('.tooltip-c').attr('id'); 
    $('.tp'+id).fadeIn(500); 
    $('.tp'+id).mouseleave(function(event){ 
     $('.tp'+id).fadeOut(300); 
    }); 
    }); 
}); 
+0

這直接解決了我的問題,我無法得到其他解決方案爲我工作。 – 2014-04-02 15:05:13

+0

比所有mouseover/mouseout解決方案效果更好,並且所有事件都可以防止默認設置。適用於IE11和Chrome。 – Arvy 2015-01-14 21:20:49