Skip to content

JS实现下拉加载、漫谈document.documentElement与document.body #13

@Quickeryi

Description

@Quickeryi

最近有一个下拉列表无限加载的需求,目前这种需求越来越多,所以这里记录一下实现原理,已经封装成一个工具方法,工参考!

原理

  • 先上图:一图抵千言

01b08eeb-144a-4f17-adaf-9d08a62cb4d2

  • 上代码:是不是很暴力
/**
 * @param warp {DOM || null} 外层容器,当为null时,默认以整个文档结构为外容器
 * @param threshold  {Number} 滚动阀值,即可以设置一个值,当滚动到离地步还有一段距离时,就开始执行callback
 * @param cb {Function} 回掉函数
 */
let scrollToLoad = (warp, threshold, cb) => {
     let scrollTop = 0,
          warpHeight,
          listHeight,
          _threshold_ = threshold || 0;
     if (!warp) {
         // 获取滚动条当前的位置 
         if (document.documentElement && document.documentElement.scrollTop) { 
            scrollTop = document.documentElement.scrollTop; 
         } else if (document.body) { 
            scrollTop = document.body.scrollTop; 
         } 
         // 获取当前可视范围的高度
         if (document.body.clientHeight && document.documentElement.clientHeight) { 
            warpHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight); 
         } else { 
            warpHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight); 
         } 

         // 获取list完整的高度
         listHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
     } else {
         scrollTop = warp.scrollTop; 
         warpHeight = warp.clientHeight;
         listHeight = warp.scrollHeight;
     }

     if (listHeight <= warpHeight + scrollTop - _threshold_) {
        cb && cb();
     }
}

document.documentElement与document.body

上面看到document.documentElementdocument.body是不是晕乎乎的呢,下面简单说明一下两者的关系与区别吧!

  • document:代表的是整个文档
  • document.documentElement:整个文档节点树的根节点,在网页中即html标签
  • document.body:整个文档DOM节点树里的body节点,网页中即为body标签元素
  • 在高级浏览器以及IE6的标准模式中(window.compatMode == 'CSS1Compat')时,document.documentElement.clinetWidthdocument.documentElement.clientHeight保存着页面视口信息,而对于混杂模式下的IE6则必须通过document.body对象获取

关于视口大小

60fe5278-6ef0-403c-a42a-691bed5dab0d

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions