最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fade out if mouse does not hover element - Stack Overflow

programmeradmin2浏览0评论

Basically I want to fade out an element if after x seconds there is no mouseover event triggered. I've tried for a few hours and just can't seem to write the code to work properly.

So far I've written -

$('.toolTip').live('mouseover', function() {
    $(this).stop(true, true).fadeIn();
});
$('.toolTip').live('mouseleave', function() {
    $(this).delay(4000).fadeOut("slow");
});

Which works if the mouse enters the div, and then leaves, but not if it doesn't ever gain focus.

Basically I want to fade out an element if after x seconds there is no mouseover event triggered. I've tried for a few hours and just can't seem to write the code to work properly.

So far I've written -

$('.toolTip').live('mouseover', function() {
    $(this).stop(true, true).fadeIn();
});
$('.toolTip').live('mouseleave', function() {
    $(this).delay(4000).fadeOut("slow");
});

Which works if the mouse enters the div, and then leaves, but not if it doesn't ever gain focus.

Share Improve this question edited Aug 10, 2012 at 4:06 nbrooks 18.2k5 gold badges56 silver badges67 bronze badges asked Aug 10, 2012 at 2:36 Jordan ParkerJordan Parker 752 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

The mouseover event will never be called on the .toolTip div because fadeOut() will finish by applying display:none to the element, thus preventing you from ever mousing over it again. Instead of fadeOut(), you can use fadeTo() to change it's opacity without affecting it's display property.

$(document).on('mouseover', '.toolTip', function() {
    $(this).stop().fadeTo("fast", 1);
});

$(document).on('mouseleave', '.toolTip', function() {
    $(this).delay(4000).fadeTo("slow", 0);
});​

One way to acplish this would be to add a fadeTo() mand in addition to your mouseover events so that it initially begins fading out:

$(".toolTip").delay(1000).fadeTo(5000, 0);
$(".toolTip").on({
    mouseleave: function() {
        $(this).delay(1000).fadeTo(5000, 0);
    },
    mouseenter: function() {
        $(this).stop().fadeTo(500, 1);
    }
});

DEMO

发布评论

评论列表(0)

  1. 暂无评论