blog icon indicating copy to clipboard operation
blog copied to clipboard

页面滚动Scroll

Open whizbz11 opened this issue 5 years ago • 0 comments

今天聊聊常用的滚动属性和方法

相关API说明

  • 滚动相关元素说明
属性 说明
element.scrollHeight 元素的整体高度
element.scrollWidth 元素的整体宽度
element.scrollLeft 元素左边缘与视图之间的距离
element.scrollRight 元素右边缘与视图之间的距离
//判定元素是否滚动到底
element.scrollHeight - element.scrollTop === element.clientHeight
//返回顶部
element.scrollTop = 0
  • scrollTo(x,y)
window.scrollTo(x-coord, y-coord)
window.scrollTo(options)

参数说明

x:把文档向右滚动的像素数。

y:把文档向下滚动的像素数。

options: 是一个ScrollToOptions参数集合,其中包括滚动横向、纵向坐标、滚动的方式

eg:

//滚动横向和纵向位置 0,1000px
window.scrollTo(0, 1000); 

//平滑到100、100这个位置
window.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});
  • scrollBy(x,y)

注意:scrollTo跟scrollBy的参数是一样的,区别就是scrollBy滚动距离是相对与当前滚动条位置进行滚动

  • scrollIntoView
element.scrollIntoView(); // 等同于element.scrollIntoView(true) 
element.scrollIntoView(alignToTop); // Boolean parameter
element.scrollIntoView(scrollIntoViewOptions); // Object parameter

参数说明

  • alignToTop (Boolean型参数)

    • 如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。
    • 如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐
  • scrollIntoViewOptions (Object型参数)

{
    behavior: "auto"  | "instant" | "smooth",
    block:    "start" | "end",
}

如何将元素滚动在可视区中

1、调用scrollTo方法

// 获取元素的offsetTop(元素距离文档顶部的距离)
let offsetTop = document.querySelector(".box").offsetTop;

// 设置滚动条的高度
window.scrollTo(0, offsetTop);

2、通过锚点

<a href="#target">点我会将内容显示到顶部</a>
<div id="target"></div>

3、scrollIntoViewOptions

document.querySelector(".target").scrollIntoView();

whizbz11 avatar Dec 27 '19 02:12 whizbz11