如何在jQuery中触发两个元素的mouseout事件?

时间:2011-12-19 05:35:20

标签: jquery events dom mouseleave

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

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

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

我试过这个

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

但是如果鼠标离开任一节点,这会触发事件。我希望一旦鼠标悬停在任一节点上,就会触发事件。

有一种简单的方法吗?我有一个想法,涉及全局变量跟踪每个div的鼠标状态,但我希望更优雅的东西。

3 个答案:

答案 0 :(得分:18)

我一直遇到这个问题,如果符合我正在做的事情,我的'快速修复'就是以下内容;

var timer;

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


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

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

答案 1 :(得分: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');
});

答案 2 :(得分: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 ..
  }
}