问题描述
大家好,我在这个脚本上使用了滚动功能,但是每次用户滚动时它都会触发.我希望它只在用户向下滚动到 #ror
时触发一次.我尝试使用 fired
变量来检查它是否已经被触发,但这似乎不起作用.我知道有些人之前已经回答过这个问题,但这是我从那里得到了被解雇的解决方案,并且不能让它只工作一次.有人认为他们可以提供帮助吗?
Hi guys I am using the scroll function on this script but it fires each time a user scrolls. I want it to only fire once when the user scrolls down to #ror
. I tried using the fired
variable to check if it has already been fired but that didn't seem to work. I know some people have answered this before but this is where i got the fired solution from and cant get it to work only once. Anyone think they can help please?
$( window ).scroll(function() {
var fired = 0;
console.log(fired);
if(fired == 0){
$('#ror').html('');
$('#ror').goalProgress({
goalAmount: 100,
currentAmount: 75,
textBefore: 'progress bar',
textAfter: '',
offset: 10,
});
fired=1;
}
});
推荐答案
要检测给定的 #target
何时滚动到视图中,您可以查看它的顶部位置,并检查该位置是否已经存在视口内.
To detect when a given #target
scrolls into view, you can look at it's top position, and check if that position is already inside the viewport.
$('#target').offset().top - $(window).outerHeight() > $(window).scrollTop();
等式的左边部分是常数(只要你不移动任何东西,或改变视口的大小).因此,将它移到事件处理函数之外可能是明智的.您需要记住滚动事件相当昂贵,因为它在您滚动时不断触发,并且浏览器已经忙于渲染视口.
That left part of the equation is constant (as long as you don't move anything around, or change the size of the viewport). Therefore it may be wise to move that outside your event handler function. You need to keep in mind that the scroll event is rather expensive, since it fires constantly when you are scrolling, and the browser is already quite busy with the rendering of the viewport.
工作完成后,您可以删除事件处理程序.
When the work is done, you can remove the event handler.
$(window).off(event);
所以你的最终代码看起来像这样:
So your final code would look something like this:
var triggerAtY = $('#target').offset().top - $(window).outerHeight();
$(window).scroll(function(event) {
// #target not yet in view
if (triggerAtY > $(window).scrollTop()) {
return;
}
// run your task
// remove this event handler
$(this).off(event);
});
看一下演示:https://jsfiddle.net/6whnfa02/1/
文档:
- http://api.jquery.com/offset/
- http://api.jquery.com/outerHeight/
- http://api.jquery.com/scrollTop/
- http://api.jquery.com/off/
这篇关于当元素变得可见时,jQuery 滚动函数会触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!