jQuery滚动多次调用一个函数 [英] jQuery scroll calls a function multiple times
问题描述
我有一个jquery滚动功能,如下所示:
I have a jquery scroll function as below :
$(window).scroll(function() {
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
alert('call me');
}
});
和HTML:
<div style="height:450px;">BOX</div>
当我滚动时,我得到的不是call me
,而是call me
.为什么会这样,怎么了?
此处的JSFiddle示例
When I scroll, instead of just one call me
I am getting multiple times call me
. Why so and whats wrong ?
JSFiddle Example Here
推荐答案
此功能不是bug,正常情况是每次滚动事件发生时都会接收它,每次滚动事件在元素中的位置都启动时会启动滚动条已更改.
It's a feature not a bug, is normal to receive it each time the scroll event happens, the scroll event is launched every time the position of an element within the scrollbars is changed.
如果不需要,可以添加一个标志,一个类或一个超时来避免它.
You can add a flag, a class or a timeout to avoid it if don't want it.
例如,在超时的情况下,您可以这样操作:
For example with a timeout you may do it like this:
var timeout;
$(window).scroll(function() {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 100);
});
function check(){
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
alert('Call me!')
}
}
小提琴在这里: http://jsfiddle.net/f3C6Y/2/
这篇关于jQuery滚动多次调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!