我尝试仅在其中一个元素 #checkPosition
到达窗口顶部时调用函数 myFunction
一次,但因为我必须使用 $(window).scroll()
来检测操作(滚动),并且在某个时刻 totalScroll
的滚动值始终大于该元素到顶部 indicatorPosition< 的距离
,函数被多次调用。
如何才能只调用该函数一次?
HTML:
<div class="section section--1">
<p>Section 1</p>
</div>
<div class="section section--2">
<p>Section 2</p>
<div id="checkPosition" class="indicator">Check position</div>
<div id="targetElement" class="target">Target: </div>
</div>
CSS(只是为了获得一些高度):
.section {
min-height: 1000px;
}
JS:
const indicatorPosition = $('#checkPosition').offset().top;
console.log("indicators initial position:", indicatorPosition);
var myFunction = function(){
$('#targetElement').append('new text goes here only once. ');
console.log("call me only once");
}
$(window).scroll(function(){
var totalScroll = $(window).scrollTop();
if (totalScroll > indicatorPosition) {
myFunction();
}
});
最佳答案
一种方法是使用变量并在调用函数时递增它,然后检查该值是否已更改以查看该函数之前是否已被调用
let indicatorPosition = $('#checkPosition').offset().top;
console.log("indicators initial position:", indicatorPosition);
var myFunction = function(){
$('#targetElement').append('new text goes here only once. ');
console.log("call me only once");
}
let check = 1
$(window).scroll(function(){
var totalScroll = $(window).scrollTop();
if (totalScroll > indicatorPosition) {
if(check === 1){
myFunction();
check++
}
}
});
.section {
min-height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section section--1">
<p>Section 1</p>
</div>
<div class="section section--2">
<p>Section 2</p>
<div id="checkPosition" class="indicator">Check position</div>
<div id="targetElement" class="target">Target: </div>
</div>
关于javascript - 仅当元素到达窗口顶部时调用函数一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109105/