【问题标题】:How can I trigger a mouseout event for two elements in jQuery?如何为 jQuery 中的两个元素触发 mouseout 事件?
【发布时间】:2012-01-23 08:33:37
【问题描述】:

假设我有两个独立的 div,A 和 B,它们在一个角落重叠:

+-----+
|     |
|  A  |
|   +-----+
+---|     |
    |  B  |
    |     |
    +-----+

我想在鼠标离开 A 和 B 时触发一个事件。

我试过了

$("#a, #b").mouseleave(function() { ... });

但是,如果鼠标离开任一节点,这将触发事件。我希望在鼠标不在任一节点上时触发事件。

有没有简单的方法来做到这一点?我有一个想法,它涉及跟踪每个 div 上的鼠标状态的全局变量,但我希望有更优雅的东西。

【问题讨论】:

  • 我以前见过这个。我认为您可以使用.offset() 为每个#a, #b 计算组合 坐标,当鼠标位置不再位于组合坐标上方时,$('#a, #b').trigger('mouseleave');
  • @JarredFarrish 这听起来比我想到的解决方案更糟糕。跟踪光标的偏移量可能非常麻烦。

标签: jquery events dom mouseleave


【解决方案1】:

我一直遇到这个问题,如果它适合我​​正在做的事情,我的“快速修复”如下;

var timer;

$("#a, #b").mouseleave(function() {
    timer = setTimeout(doSomething, 10);
}).mouseenter(function() {
    clearTimeout(timer);
});


function doSomething() {
    alert('mouse left');
}

小提琴:http://jsfiddle.net/adeneo/LdDBn/

【讨论】:

  • +2.5 这很漂亮!我喜欢你只需要一个全局变量,而且这个过程不需要像更明显的解决方案那样费劲。
  • 如果您可以绝对定位其中一个元素,则不需要像这样的 hack。见here
  • @muhd -绝对位置与它无关,这是事件传播,当你嵌套这样的元素时会发生这种情况,但答案是作为嵌套的替代方案,因为这并不总是可能的。
  • 你的快速修复对我来说似乎是非常快速的解决方案:)
【解决方案2】:

如果您将第二个容器嵌套在第一个容器中,则无需复杂的 jQuery 解决方案:

http://jsfiddle.net/5cKSf/3/

HTML

<div class="a">
    This is the A div
    <div class="b">
        This is the B div
    </div>
</div>

CSS

.a {
    background-color: red;
    width: 100px;
    height: 100px;
    position: relative;
}

.b {
    background-color: blue;
    width: 100px;
    height: 100px;
    position:absolute;
    top: 50px;
    left: 50px;
}

JS

$('.a').hover(function() {
   alert('mouseenter'); 
}, function() {
   alert('mouseleave');
});

【讨论】:

    【解决方案3】:

    我想您可以使用以下方法实现此目的:

    var mouseLeftD1 = false;
    var mouseLeftD2 = false;
    
    $('#d1').mouseleave(function() {
      mouseLeftD1 = true;
      if(mouseLeftD2 == true) setTimeout(mouseLeftBoth, 10);
    }).mouseenter(function() {
      mouseLeftD1 = false;
    });
    
    $('#d2').mouseleave(function() {
      mouseLeftD2 = true;
      if(mouseLeftD1 == true) setTimeout(mouseLeftBoth, 10);
    }).mouseenter(function() {
      mouseLeftD2 = false;
    });
    
    function mouseLeftBoth() {
      if(mouseLeftD1 && mouseLeftD2) {
        // .. your code here ..
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多