问题
I just want the #menu
to fade when the scroll bar is moving to provide a less cluttered interface. Is there code that would allow this?
I guess basically what I'm looking for is how to grab the scroll bar movement event. To slowly fade out the #menu
after 1 seconds of scrolling and bring back the #menu
after 2 second of scroll-bar inactivity.
Thank you so much!
回答1:
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.
回答2:
Right using the following:
$('body').scroll(function(){
$('#menu').fadeOut();
var scrollA = $('body').scrollTop();
setTimeout(function(){
if(scrollA == $('body').scrollTop()){
$('#menu').fadeIn();
}
}, 200);
})
So we record the scroll amount, wait 200 milliseconds and then see if the scroll has changed, if not we fade the menu back in.
回答3:
I think this is what you are looking for http://jsfiddle.net/wfPB6/
来源:https://stackoverflow.com/questions/7390960/how-to-hide-a-div-when-the-scroll-bar-is-moving-with-jquery