【问题标题】:ignore Mouseout event from child element of Mouseover element忽略来自 Mouseover 元素的子元素的 Mouseout 事件
【发布时间】:2012-04-22 09:14:43
【问题描述】:

我需要在鼠标悬停时显示图像的工具提示。我为此编写了以下代码。我当前的问题是,当我将图像放入工具提示 div 时,该事件仅针对图像元素发生。如何忽略来自父工具提示 div 的子元素的 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);
            });
        });
    });

请帮帮我。我很无奈。

【问题讨论】:

  • 如何忽略来自 Mouseover 元素的子元素的 Mouseout 事件?
  • 哪个孩子?答案无法以当前形式回答。
  • 对不起,伙计们..我会编辑问题。
  • @GihanDilusha,我猜人们还在等待你的 HTML 代码。很难假设是什么。

标签: jquery mouseevent mouseover event-bubbling dom-events


【解决方案1】:

尝试改用.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);
    });
  });
});

【讨论】:

  • 这立即解决了我的问题,我无法让其他解决方案为我工作。
  • 比所有 mouseover/mouseout 解决方案效果更好,并且所有事件都阻止默认值。在 IE11 和 Chrome 上运行正常。
【解决方案2】:

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

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

【讨论】:

  • @Gihan Dilusha 在您的事件处理函数参数中传递eevent,然后使用.stopPropagation 作为其方法。
  • 我什至用过。但它是一样的:(
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2017-01-31
  • 2014-11-17
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
相关资源
最近更新 更多