仅滚动一次调用函数 [英] Call function on scroll only once
问题描述
我得到一个关于如果对象在我的屏幕内将被调用的函数的问题。但是当对象在我的屏幕内时,该函数被调用并且已触发警报。但是,如果我关闭警报并向下滚动,则会再次调用该事件。我不要那个。我该如何解决?
I got a question regarding a function that will be called if the object is within my screen. But when the object is within my screen the function is been called and a alert is been fired. But if I close the alert and scroll further down the event is called again. I do not want that. How can I solve that?
到目前为止我的代码:
<div id="wrapper">
scroll down to see the div
</div>
<div id="tester"></div>
JS
$(window).on('scroll',function() {
if (checkVisible($('#tester'))) {
alert("Visible!!!")
} else {
// do nothing
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
我想要的是If函数只会被调用1次而不是如果对象可见,则在每个滚动上。
What I want is that the If function only will be called 1 time and not on every scroll if the object is visible.
推荐答案
尝试使用 .one()
:
$(window).one('scroll',function() {
// Stuff
});
或者,取消内部事件的链接:
Or, unlink the event inside:
$(window).on('scroll',function() {
// After Stuff
$(window).off('scroll');
});
猜猜您需要此代码:
$(window).on('scroll',function() {
if (checkVisible($('#tester'))) {
alert("Visible!!!");
$(window).off('scroll');
} else {
// do nothing
}
});
小提琴: http://jsfiddle.net/c68nz3q6/
Fiddle: http://jsfiddle.net/c68nz3q6/
这篇关于仅滚动一次调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!