简体   繁体   English

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

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

How can I automatically execute a JavaScript function when the user reaches a specific position on the page? 当用户到达页面上的特定位置时,如何自动执行JavaScript函数?

When I scroll down to the bottom of the page, an AJAX-call shall be executed that loads more content so that you can scroll down further. 当我向下滚动到页面底部时,将执行AJAX调用,该调用将加载更多内容,以便您可以进一步向下滚动。

Nothing should happen if the user scrolls down and then scrolls up again by the same distance. 如果用户向下滚动然后再次向上滚动相同的距离,则不会发生任何事情。

This is the call of the ajax function that I have and want to execute: 这是我要执行的ajax函数的调用:

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

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

HTML: HTML:

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

JavaScript, will alert when page reaches "anotherElement": 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);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM