2018年 js 简易控制滚动条滚动的简单方法

首先是es2015 的新api

Element.scrollIntoView()  // 滚动到最上方 等同于 dom.scrollIntoView(true) 
Element.scrollIntoView(false) // 滚动到最下方
文档地址
![https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView)

还有一个WebKit专有的方法

element.scrollIntoViewIfNeeded();
element.scrollIntoViewIfNeeded(true);
element.scrollIntoViewIfNeeded(false);

// 如果为true,则元素将在其所在滚动区的可视区域中居中对其。
// 如果为false,则元素将与其所在滚动区的可视区域最近的边缘对齐。 根据可见区域最靠近元素的哪个边缘,元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。
文档地址
![https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoViewIfNeeded](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoViewIfNeeded)

不考虑浏览器兼容的小伙伴们可以随意使用了

通用的,精确的方法
使用scrollTop scrollLeft
比如document.querySelector("header-nav").scrollLeft = 20 // 导航栏往右滚20px
比如document.querySelector("main").scrollTop = 20 // 内容区往下滚20px

注意,得出现滚动条才能滚动,如果不能滚动,尝试下再父级添加高度或宽度,overflow:auto

原文地址:https://www.cnblogs.com/daowangzhizhu-pt/p/8146477.html