JS如何判断滚动条是否滚到底部
发布日期:2022-02-24 11:35:56 浏览次数:7 分类:技术文章

本文共 2660 字,大约阅读时间需要 8 分钟。

基本概念:

网页可见区域宽: document.body.clientWidth; 网页可见区域高: document.body.clientHeight; 网页可见区域宽: document.body.offsetWidth   (包括边线的宽); 网页可见区域高: document.body.offsetHeight  (包括边线的宽); 网页正文全文宽: document.body.scrollWidth; 网页正文全文高: document.body.scrollHeight; 网页被卷去的高: document.body.scrollTop; 网页被卷去的左: document.body.scrollLeft; 网页正文部分上: window.screenTop; 网页正文部分左: window.screenLeft; 屏幕分辨率的高: window.screen.height; 屏幕分辨率的宽: window.screen.width; 屏幕可用工作区高度: window.screen.availHeight; 屏幕可用工作区宽度:window.screen.availWidth;

关于offset共有5个东西需要弄清楚:

  1. offsetParent
  2. offsetTop
  3. offsetLeft
  4. offsetWidth
  5. offsetHeight

offsetWidth与offsetHeight

也就是元素的可视宽度,这个宽度包括元素的边框(border),水平padding,垂直滚动条宽度,元素本身宽度等

offsetWidth=(border-width)*2+(padding-left)+(width)+(padding-right)。offsetHeight=(border-width)*2+(padding-top)+(height)+(padding-bottom)

offsetLeft与offsetTop

返回对象元素边界的左上角顶点相对于offsetParent的左上角顶点的水平偏移量。从这个定义中我们可以明确地知道offsetLeft与当前元素的margin-left和offsetParent的padding-left有关

offsetLeft=(offsetParent的padding-left)+(中间元素的offsetWidth)+(当前元素的margin-left)。offsetTop=(offsetParent的padding-top)+(中间元素的offsetHeight)+(当前元素的margin-top)

offsetParent

  1. 如果当前元素的父级元素没有进行CSS定位(position为absolute或relative),offsetParent为body。
  2. 如果当前元素的父级元素中有CSS定位(position为absolute或relative),offsetParent取最近的那个父级元素。

滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。

function getScrollTop(){  var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;  if(document.body){    bodyScrollTop = document.body.scrollTop;  }  if(document.documentElement){    documentScrollTop = document.documentElement.scrollTop;  }  scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;  return scrollTop;}//文档的总高度function getScrollHeight(){  var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;  if(document.body){    bodyScrollHeight = document.body.scrollHeight;  }  if(document.documentElement){    documentScrollHeight = document.documentElement.scrollHeight;  }  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;  return scrollHeight;}function getWindowHeight(){  var windowHeight = 0;  if(document.compatMode == "CSS1Compat"){    windowHeight = document.documentElement.clientHeight;  }else{    windowHeight = document.body.clientHeight;  }  return windowHeight;}window.onscroll = function(){  if(getScrollTop() + getWindowHeight() == getScrollHeight()){    alert("已经到最底部了!!");  }};//jquery$(window).scroll(function(){  var scrollTop = $(this).scrollTop();  var scrollHeight = $(document).height();  var windowHeight = $(this).height();  if(scrollTop + windowHeight == scrollHeight){    alert("已经到最底部了!");  }});

转载地址:https://blog.csdn.net/hulinhulin/article/details/121260405 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:网站信息的采集系列(二)--百度搜索内容的采集
下一篇:网站模拟登录总结

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月12日 22时22分26秒