• 深入探究,代码分析关于JS实现滚动到底部加载


    实现原理与分析:

      要实现滚动到底部或者顶部执行,需要3个元素

      1.要获取滚动条垂直滚动的的距离

      2.获取整个文档(页面)的整体高度

      3.获取窗口可视区域的高度

      当滚动条滚动的值为0的时候,那么就是在顶部,如果值大于或者等于文档高度减去窗口可视区域的高度,那么就为底部

      

    具体实现方法:

      一、使用原生JS实现

     

        window.onscroll = function(){
        //滚动的值
           let documentTop = document.documentElement.scrollTop;
          // 文档高度
          let documentH = document.body.scrollHeight;
          let windowH = document.documentElement.clientHeight;
          if (documentTop === 0) {
              console.log('已经到顶部')
          }
          if (documentTop >= documentH - windowH) {
              console.log(documentTop+"滚动条已经到达底部")
          }
      };    

      二、使用jQuery里实现
      // 代码拆分:
      //1.$(document).scrollTop()是获取垂直滚动的距离 (即当前滚动的地方的窗口顶端到整个页面顶端的距离),当它为0的时候就是到了页面顶端
      //2.要获取底端 只要获取$(document).scrollTop()>=$(document).height()-$(window).height()就可以知道已经滚动到底端了
      //3.$(window).height()代表了当前可见区域的大小
      //4.$(document).height()则代表了整个文档的高度,一般情况下是固定不会改变的,但是在做滚动加载的时候,会不断的加大文档高度
       主要代码:

      $(window).scroll(function() {
          if ($(document).scrollTop() === 0) {
      console.log('已经到顶部')
      }
      if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
      console.log("滚动条已经到达底部为" + $(document).scrollTop())
      }
      })

    在项目使用的时候遇到了一个坑,在普通页面使用的时候,都是没有问题的,但是有一次放进了vuecli项目中的时候,怎么都不执行,找了很久没有找到原因,最后将发现外层div的height设置为了100%,去掉之后就能
    正常执行了,上诉代码都是经过我测试过的,放进页面就能执行,如果不能正常执行,请检查一下是否是样式影响了代码。
  • 相关阅读:
    【leetcode】Climbing Stairs (easy)
    【leetcode】Best Time to Buy and Sell 3 (hard) 自己做出来了 但别人的更好
    【leetcode】Best Time to Buy and Sell 2(too easy)
    【leetcode】Best Time to Buy and Sell (easy)
    【leetcode】Single Number II (medium) ★ 自己没做出来....
    【leetcode】Single Number (Medium) ☆
    【leetcode】Valid Sudoku (easy)
    【leetcode】Two Sum (easy)
    Oracle-11-主键约束
    Codeforces444A_DZY Loves Physics
  • 原文地址:https://www.cnblogs.com/qiuchuanji/p/8778070.html
Copyright © 2020-2023  润新知