我尝试仅在其中一个元素myFunction
点击窗口顶部时调用函数#checkPosition
,但因为我必须使用$(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();
}
});
答案 0 :(得分:3)
一种方法是使用变量并在调用函数时递增它,然后检查值是否已更改以查看函数是否已被调用
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>