当用户到达页面中的特定元素时,如何执行JS函数? [英] How to execute a JS function when the user reaches a specific element in the page?

查看:70
本文介绍了当用户到达页面中的特定元素时,如何执行JS函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I automatically execute a JavaScript function when the user reaches a specific position on the page?

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

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.

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

Nothing should happen if the user scrolls down and then scrolls up again by the same distance.

这是我要执行的ajax函数的调用:

This is the call of the ajax function that I have and want to execute:

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

推荐答案

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

Fixed for default 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"时将发出警报:

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

这篇关于当用户到达页面中的特定元素时,如何执行JS函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆