2011-12-19 64 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'); 
});