很简单好用的方法,直接上代码:
document.getElementById(50).scrollIntoView({behavior: 'smooth', //顺滑的滚动block: 'center', //容器上下的中间inline: 'start', //容器左右的左边})
上述代码的运行结果:
scrollIntoView()
方法将调用它的元素滚动到浏览器窗口的可见区域,但是前提是它的容器可滚动
浏览器支持如下:
不支持的话,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:
nearest 就是用最小的距离把元素带到你的视野中,本来在上面就滚动到最上面,在下面就滚动到最下面,本来在视野中就不动,这样子。