滚动到div底部的底部会触发警报(纯JavaScript)

时间:2018-09-14 08:54:36

标签: javascript

我知道这里已经有解决方案,但是大多数解决方案都是用jQuery编写的,而JS版本是基于窗口的,但是我需要一种可行的方法

出于div和个人原因,我需要使用纯JavaScript进行此操作。因此,基本上,当用户在div调用a中一直滚动到底部时,我需要触发一个警报,而我并不是为了清除混乱而引用窗口的滚动条。

document.querySelector('#a').addEventListener('scroll',scrollTrigger);

function scrollTrigger(){
  if(???){
    alert('End of scroll');
  }
}
#a{
  background-color: red;
  height: 500px;
  width: 500px;
  overflow: auto;
}
<div id='a'>
  <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
   <h1>a</h1>
</div><!--</a>-->

2 个答案:

答案 0 :(得分:3)

document.querySelector('#a').addEventListener('scroll', scrollTrigger);

function scrollTrigger() {

  var el = this;
  var sc = el.scrollHeight - el.clientHeight - el.scrollTop;
  console.clear(); console.log(sc)

  if (sc === 0) {
    console.log('End of scroll');
  }
}
#a {
  height: 180px;
  overflow: auto;
}
<div id='a'>
  <h1>a---</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a---</h1>
</div>

相反,如果您要使用0...1

中的值
var sc =  el.scrollTop / (el.scrollHeight - el.clientHeight );

1将指示元素已完全滚动:

document.querySelector('#a').addEventListener('scroll', scrollTrigger);

function scrollTrigger() {

  var el = this;
  var sc = el.scrollTop / (el.scrollHeight - el.clientHeight);
  console.clear(); console.log(sc)

  if (sc === 1) {
    console.log('End of scroll');
  }
}
#a {
  height: 180px;
  overflow: auto;
}
<div id='a'>
  <h1>a---</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a</h1>
  <h1>a---</h1>
</div>

* 100,您有百分比;)

答案 1 :(得分:0)

尝试一下

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
        // you're at the bottom of the page
         console.log("Bottom of page");
     }
};