判断页面是否滚动到底部或者指定元素位置

2017-01-11  本文已影响0人  btfrankenstein

该判断是实现页面滚动到底部自动加载更多功能的必要条件,先看代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>scorll</title>
    <style>
      .main {
        background-color: red;
        height: 3000px;
      }
      .bottom {
        background-color: black;
        height: 30px;
      }
    </style>
  </head>
  <body>
    <div class="main">
    </div>

    <div class="bottom">
    </div>

    <script type="text/javascript">
      // ...
    </script>
  </body>
</html>

.bottom 在页面底部,现在添加js代码来判断页面是否滚动到 .bottom 元素

方法一

使用 getBoundingClientRect() 来判断位置

window.onload = function() {

  var windowHeight = document.documentElement.clientHeight // 视窗高度-也就是浏览器可视区域高度
  var threshold = 20 // 可以指定提前加载的距离
  var lock = false // 如果到达指定位置,则不再执行打印log

  window.addEventListener('scroll', function() {
    // getBoundingClientRect()-得到矩形元素的界线
    // 返回的是一个对象,包含 top, left, right, 和 bottom四个属性值
    // 大小都是相对于文档视图()浏览器可视区域)左上角计算而来
    var targetRect = document.getElementsByClassName('bottom')[0].getBoundingClientRect()

    //getBoundingClientRect()的top属性-目标元素离视窗顶部的距离
    var targetTop = targetRect.top

    if(lock) {
      return
    } else {
      // 如果目标元素离视窗顶部的距离小于视窗高度
      // 则表示已滚动到目标元素位置
      if(targetTop < (windowHeight + threshold)) {
        lock = true
        console.log('bottom')
      }
    }
  })
}

方法二

使用 scrollTopoffsetTop 来判断位置

window.onload = function() {

  var windowHeight = document.documentElement.clientHeight
  var threshold = 20 //指的是提前加载的距离
  var lock = false

  window.addEventListener('scroll', function() {

    var scrollBarTop = document.body.scrollTop // 滚动条离页面顶端的距离
    var targetTop = document.getElementsByClassName('bottom')[0].offsetTop // 目标元素离页面顶端的距离

    // 如果目标元素离页面顶端的距离小于视窗高度+滚动条离页面顶端的距离
    // 则表示已滚动到目标元素位置
    if(lock) {
      return
    } else {
      if(targetTop < (windowHeight + scrollBarTop + threshold)) {
        lock = true
        console.log('bottom')
      }
    }
  })
}
上一篇下一篇

猜你喜欢

热点阅读