13

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

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

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

我试过这个

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

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

是否有捷径可寻?我有一个想法,它涉及跟踪每个 div 上的鼠标状态的全局变量,但我希望有更优雅的东西。

4

3 回答 3

20

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

var timer;

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


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

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

于 2011-12-19T05:54:37.840 回答
3

如果将第二个容器嵌套在第一个容器中,则不需要复杂的 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');
});
于 2013-07-11T22:27:15.673 回答
0

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

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 ..
  }
}
于 2011-12-19T05:51:22.100 回答