很简单好用的方法,直接上代码:
document.getElementById(50).scrollIntoView({
behavior: 'smooth', //顺滑的滚动
block: 'center', //容器上下的中间
inline: 'start', //容器左右的左边
})
上述代码的运行结果:
scrollIntoView()
方法将调用它的元素滚动到浏览器窗口的可见区域,但是前提是它的 容器可滚动
浏览器支持如下:
特征 | Chrome | Firefox | Safari | Edge | IE | Opera |
---|---|---|---|---|---|---|
基本支持( alignToTop ) | yes | yes | yes | yes | yes | yes |
scrollIntoViewOptions | yes | yes | 5.1[1] | 12[1] | 9[1] | 48[2] |
不支持的话,behavior 的 smooth 和
block、inline 的 center 好像会失效
简单的使用方法( alignToTop ):
也是得到了良好支持的方法,各大浏览器基本都能用:
document.getElementById(50).scrollIntoView() //等同于true,容器的最上方,容器左右的最近点
document.getElementById(50).scrollIntoView(true) //等同于参数{block: "start", inline: "nearest"},容器的最上方,容器左右的最近点
document.getElementById(50).scrollIntoView(false) //等同于参数{block: "end", inline: "nearest"},容器的最下方,容器左右的最近点
参数用法见下 参数讲解
用到 scrollIntoViewOptions:
scrollIntoViewOptions | 可选 |
---|---|
behavior 过渡动画 | "auto","instant"(直接过去)或"smooth"(顺滑的过去),默认为"auto"。 |
block 滚动至容器上下位置 | "start","center","end"或"nearest"(最近的位置),默认为"center"。 |
inline 滚动至容器左右位置 | "start","center","end"或"nearest"(最近的位置)。默认为"nearest"。 |
nearest 就是用最小的距离把元素带到你的视野中,本来在上面就滚动到最上面,在下面就滚动到最下面,本来在视野中就不动,这样子。