【问题标题】:Call function only once when element hits top of the window当元素到达窗口顶部时仅调用一次函数
【发布时间】:2018-04-30 22:35:29
【问题描述】:

当元素之一 #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();
    }
});

【问题讨论】:

  • 为什么,如果这个值始终保持不变?

标签: javascript jquery scroll scrolltop


【解决方案1】:

一种方法是使用一个变量并在调用函数时对其进行递增,然后检查值是否已更改以查看之前是否已调用该函数

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>

【讨论】:

  • 完美运行!谢谢你。你有没有写过我不应该为 $('#checkPosition').offset().top; 使用 const 的评论? ?如果有,为什么?
  • @miss.emenems 我很糟糕,我教了值变化,我确实把它读为 scrollTop()
  • 啊,谢谢!我正在尝试学习如何正确使用 const、let 和 var,所以这就是我要问的原因:)再次感谢。我今天花了一些时间尝试不同的方法来解决这个问题,这个想法很简单而且效果很好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多