scrollTop,scrollHeight,scrollTo和innerHeight,outerHeight,clientHeight

553 阅读1分钟

scrollTop

Element.scrollTop 属性可以获取设置一个元素的内容垂直滚动的像素数。

获取滚动条距离最顶部的距离.

scrollHeight

Element.scrollHeight 属性是一个只读属性。

返回该元素的像素高度

如获取html整个文档的高度:document.documentElement.scrollHeight

scrollTo()

element.scrollTo(), 这是一个方法,

使滚动条滚动到指定的位置

语法:

element.scrollTo(x-coord, y-coord)
element.scrollTo(options)

例子

element.scrollTo(0, 1000);

使用 options:

element.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

案例

移动端Vue项目滑动到底部时候,上拉加载更多。

mounted(){
    // 每一次滚动监听scroll事件
    document.addEventListener('scroll',()=>{
      var top = document.documentElement.scrollTop; // 滚动条隐藏部分的页面高度;
      var clientHeight = document.documentElement.clientHeight; // 显示的可视内容高度
      var h = document.documentElement.scrollHeight; // 页面高度

      if(top + clientHeight + 80 > h){
        console.log(top);
      }
    })
}

innerHeight、outerHeight

都是window的属性

inner窗口的文档显示区的高度(不包括工具条)

outer 浏览器窗口的文档显示区的高度(包括浏览器的工具条)。

可理解为:文档的可视区域+浏览器窗口的工具条 。

window.innerHeight
window.innerWidth

window.outerHeight
window.outerWidth

clientHeight

Element元素的属性

窗口的文档显示区的高度(不包括工具条)