1.给顶部的div加一个id
<div id="content">
<div style="width:100%;height:900px;position:relative">
<button @click="returnTop" style="position:absolute;bottom:10px;left:0">返回顶部</button>
</div>
</div>
2.某事件触发,回到顶部
returnTop(){
content.scrollIntoView()
}
这样就直接返回到页面顶部,真的超级方便
scrollIntoView详解
该scrollIntoView()
方法将调用它的元素滚动到浏览器窗口的可见区域。
PS:页面(容器)可滚动时才有用!
- 语法:
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); //布尔参数
element.scrollIntoView(scrollIntoViewOptions); //对象参数
- 语法参数:
alignToTop | [可选],目前之前这个参数得到了良好的支持 |
---|---|
true | 元素的顶部将对齐到可滚动祖先的可见区域的顶部。对应于scrollIntoViewOptions: {block: "start", inline: "nearest"} 。这是默认值 |
false | 元素的底部将与可滚动祖先的可见区域的底部对齐。对应于scrollIntoViewOptions: {block: "end", inline: "nearest"} 。 |
- 浏览器兼容性:
特征 | 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] |
注意:不支持"smooth"
行为或"center"
选项。