var $menu = $("#menu");
var opacity = $menu.css("opacity");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$menu.animate({ opacity: 1 }, "slow");
}, 2000);
};
$(window).scroll(function () {
if (!$menu.is(":animated") && opacity == 1) {
$menu.animate({ opacity: 0 }, "slow", fadeInCallback);
} else {
fadeInCallback.call(this);
}
});
http://jsfiddle.net/zsnfb/9/
This sets the scroll event to do a few things. First it clears a timeout to fade the menu div back in. After that, if the menu isn't already faded out, it fades the menu out and sets the timeout in the callback. If the menu is already faded out, it just sets the timeout. If the user stops scrolling, the menu will fade back in after 2 seconds.
There are other solutions that use fadeOut() and fadeIn(). My only issue with those functions in this case is that setting display: none;
to the menu div will affect the layout of the page, where setting visibility: hidden;
or opacity: 0;
shouldn't affect the layout.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…