$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
$("body").css('background-color', 'red')
$.data(this, 'scrollTimer', setTimeout(function() {
$("body").css('background-color', 'white')
console.log("Haven't scrolled in 250ms!");
}, 250));
});
body {
height: 5000px;
width: 100px;
overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body></body>
归功于这个答案:
jQuery scroll() detect when user stops scrolling
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
$("body").css('background-color', 'red')
$.data(this, 'scrollTimer', setTimeout(function() {
$("body").css('background-color', 'white')
console.log("Haven't scrolled in 250ms!");
}, 250));
});
只是为了分解正在发生的事情:
1) 在window 对象上附加一个scroll 事件监听器。并传递给它一个在该事件上执行的函数。
$(window).scroll(function(){})
2) clearTimeout 与 setTimeout 齐头并进。如果你打开浏览器的开发者控制台并输入
$(window).data()
它应该返回一个空对象,因为您可能还没有为它分配任何东西。现在,如果你输入
$(window).data('myData', 'my_value')
$(window).data() //=> returns an -> Object {myData: "my_value"}
你也可以像$.data(element)这样访问元素的数据:
$.data(window) //=> returns an -> Object {myData: "my_value"}
对#clearTimeout 的第一次调用是针对空属性调用的,因为尚未将scrollTimer 分配给window.data() object。
3) 设置元素的颜色。在这种情况下,我以body 为例,但您需要输入正确的选择器:
$('body').css('background-color', 'red')
4) 使用#setTimeout函数在时间过去后返回原始颜色。
$.data(this, 'scrollTimer', setTimeout(function() {
$('body').css('background-color', 'white')
console.log("Haven't scrolled in 250ms!");
}, 250));
函数里面的this,代表window:
$.data(this, 'scrollTimer', setTimeout(function() {...}, 250)
等同于:
$.data(window, 'scrollTimer', setTimeout(function() {...}, 250)
它正在访问window对象中的数据
PS:为了让 sn-p 工作,您可能必须全屏显示