2011-12-19 67 views
11

让我们假设我有两个spearate的div,A和B,在拐角处重叠:如何触发jQuery中两个元素的mouseout事件?

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

我要当鼠标离开 A和B.

我试图触发事件这

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

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

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

+1

我以前见过这个。我认为你可以使用'.aset()'计算每个'#a,#b'的*组合坐标,当鼠标位置不再位于组合坐标上时,['$('#a,#b ').trigger(' 鼠标离开'); '](http://api.jquery.com/trigger/)。 – 2011-12-19 05:41:36

+0

你可以做一个小提琴 – Rafay 2011-12-19 05:50:08

+0

@JarredFarrish这听起来更糟,我想到的解决方案。跟踪光标的偏移量可能相当笨拙。 – 2011-12-19 06:12:27

回答

17

我遇到这个问题的时候,我的“速战速决”;

var timer; 

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


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

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

+0

伟大的解决方案! – Murtaza 2011-12-19 05:59:06

+0

+2.5这很漂亮!我喜欢你如何只需要一个全局变量,而且这个过程并不需要像更明显的解决方案那么简单。 – 2011-12-19 06:00:41

+0

+1为优雅。 – techfoobar 2011-12-19 06:05:30

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 .. 
    } 
} 
+0

我错误地给了upvote,所以我必须再次downvote – Murtaza 2011-12-19 12:36:01

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'); 
});