我使用了一个插件"isInViewport js",它可以让你知道元素何时在视口中,并让你在发生这种情况时做一些事情。
所以我写了一个计数函数,它是一个数字计数器函数。当元素earn位于视口中时,将执行此操作。
但是每次元素进入视口时,此计数函数都会开始执行。我希望这个函数执行不超过一次。
这是我编写的代码,运行良好,但不符合我的预期:
$('.earn').on('inview', function (event, visible) {
console.log('inview');
if (visible == true) {
console.log('inview count');
counting();
} else {
$('#counter').text(0);
$('#counter2').text(0+"$");
}
});
我正在寻找的 puseocode 是:
if(count of function == 0){
executeFunction();
}
else{
}
有人可以通过javascript或jquery为此提供解决方案吗?
如果你只需要counting
运行一次,你可以在inview
处理程序中做这样的事情。
if (visible == true) {
console.log('inview count');
if (!this.is_counted) { // 'this' should refer to your element.earn
counting();
this.is_counted = true;
}
}