1

我是菜鸟,jQuery我想了解当鼠标离开另一个元素时如何知道我的鼠标悬停在一个元素中。

我写了这段代码:

html

<ul>
    <li class="conver">1</li>
    <li class="conver">2</li>
    <li class="conver">3</li>
    <li class="conver">4</li>
    <li class="conver">5</li>
</ul>
<div id="center">JSFIDDLE</div>

jQuery

$('ul').on('mouseenter','li', function () {
        $('#center').fadeIn('fast');

}).on('mouseleave','li', function () {
     //I want when mouse leave this element if mouse doesn't hover on ('#center') 
     //element so hide ('#center') element but if to be hover on it this div keep on
     //and don't hide
        $('#center').stop().fadeOut('fast');
});

现在告诉我,我如何知道鼠标离开li元素何时在('#center')元素

4

2 回答 2

0

尝试这个

timerId = null;
$('ul').on('mouseenter','li', function () {
        $('#center').fadeIn('fast');

}).on('mouseleave','li', function () {
     //I want when mouse leave this element if mouse doesn't hover on ('#center') 
     //element so hide ('#center') element but if to be hover on it this div keep on
     //and don't hide
     timerId = setTimeout(function(){
                     $('#center').stop().fadeOut('fast');
               }, 500);

});

$('#center').on('mouseenter', function(){
     if(timerId){
        cleatTimeout(timerId);
        timerId = null;
     }
});
于 2013-08-20T09:58:56.330 回答
0

我认为这会奏效。请记住,缓存 jquery 选定对象是一个好习惯。例如 $('#center') 在您的代码中多次使用。

var center = $('#center');
var ul = $('ul');
var isMouseOnCenter = false;
ul.on("mouseenter", function () {
    center.stop().fadeIn('fast');
}).on("mouseleave", function() {
    isMouseOnCenter = false;
    setTimeout(function() {
        if(!isMouseOnCenter)
            center.stop().fadeOut('fast');
    }, 300);    
});
center.on("mouseenter", function() {
    isMouseOnCenter = true;
});

这是上面代码的 js fiddle http://jsfiddle.net/krasimir/cWn65/1/

还有一个小故障,因为您将事件附加在li标签上。上ul不是更好吗?

于 2013-08-20T10:03:08.253 回答