对于滚动元素的操作,我们都知道,先用选择器选中滚动元素,然后调用几个滚动方法(scroll, scrollTo, scrollBy)即可,但是页面滚动条如何控制,接下来就举例一波
window.scrollTo(0, 50) //横向移动到0,纵向移动到距离顶点50px处
document.querySelector('html').scrollTo(0, 50) //同上
document.querySelector('html').scrollTop = 50 //纵向移动到距离顶点50px处**
window.scrollBy(0, 50) //从当前位置,横向移动0,纵向移动50px
document.querySelector('html').scrollBy(0, 50) //同上
另外 scroll 方法和 scrollTo 用法和功能是一样的,即widnow.scroll(0, 50) 和 widnow.scrollTo(0, 50) 一样
补充:
window.scrollY //获取纵向高度(只读)
document.querySelector('html').scrollIntoView() //页面滚动到最上边
document.querySelector('html').scrollIntoView(false) //页面滚动到最下边
scrollIntoView 方法的详细用法可参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView