当用户到达页面中的特定元素时,如何执行JS函数

How to execute a JS function when the user reaches a specific element in the page?

本文关键字:何执行 执行 函数 JS 元素 用户      更新时间:2023-09-26

当用户到达页面上的特定位置时,我如何自动执行JavaScript函数?

当我向下滚动到页面底部时,将执行AJAX调用,加载更多内容,以便您可以进一步向下滚动。

如果用户向下滚动,然后再向上滚动相同的距离,则不会发生任何事情。

这是我拥有并想要执行的ajax函数的调用:

refresh('refresh_status', 'refresh_status.php', '', '', '', 'refresh');

已修复默认JavaScript:http://cdpn.io/xdjmG

HTML:

<div id="page" style="min-height: 10000px;">
    <div id="anotherElement" style="margin-top: 500px; min-height: 500px; background-color:red"></div>
</div>

JavaScript,当页面到达"anotherElement"时会发出警报:

window.addEventListener('scroll', function(){
  var place = document.body.scrollTop;
  var alertOn = document.getElementById('anotherElement').offsetTop;
  if(place > alertOn){
    alert('Function execute here');
    this.removeEventListener('scroll', arguments.callee, false);
  }
});