javascript jQuery 滚动事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14250661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery scroll event
提问by user1965451
I am trying the following jQuery code.
When I scroll either up or down I want to fadeOut
a div and when the scroll has stopped fadeIn
the same div.
我正在尝试以下 jQuery 代码。
当我向上或向下滚动时,我想要fadeOut
一个 div,并且当滚动停止时fadeIn
相同的 div。
What I have is this:
我有的是这样的:
$(document).ready(function(){
$(window).scroll(function(e){
$('#search_tab').fadeOut('slow');
});
});
I know that this will fadeOut
the div when the scroll has started, but the trick is to fade it back once I stop scrolling.
我知道这将fadeOut
在滚动开始时显示 div,但诀窍是在我停止滚动后将其淡出。
Now, I have seen this(but still not quite what I want)
现在,我已经看到了这个(但仍然不是我想要的)
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
The above function will not work at all as follows:
上面的函数将完全不起作用,如下所示:
$(window).bind('DOMMouseScroll', function(e){
if(e.detail > 0) {
//scroll down
$('#search_tab').fadeOut('slow');
}else {
//scroll up
$('#search_tab').fadeOut('slow');
}
//prevent page fom scrolling
return false;
});
采纳答案by Blake Plumb
There isn't a scrollstop
listening event but you can emulate one by using a setTimeout()
function and then clearing the timer
every time the page scrolls. Here is a sample fiddle.
没有scrollstop
监听事件,但您可以通过使用一个setTimeout()
函数来模拟一个,然后在timer
每次页面滚动时清除它。这是一个示例小提琴。
var timer;
$(window).scroll(function(e){
clearTimeout(timer);
$('#search_tab').fadeOut('slow');
timer = setTimeout(checkStop,150);
});
function checkStop(){
$('#search_tab').fadeIn('slow');
}
回答by Nick Jonas
You can check on every frame:
您可以检查每一帧:
// shim for frame listener
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// on every frame, call render()
(function animloop(){
requestAnimFrame(animloop);
render();
})();
var lastScroll = 0, isScrolling = false;
function render(){
var thisScroll = $(window).scrollTop();
if(lastScroll !== thisScroll){
if(!isScrolling){
// scrolling has started, fade out div
$('#search_tab').stop().fadeOut('slow');
}
isScrolling = true;
}else{
if(isScrolling){
// scrolling has stopped, fade in div
$('#search_tab').stop().fadeIn('slow');
}
isScrolling = false;
}
lastScroll = thisScroll;
}