第一种:常见 锚链接,id
和 href
结合起来
<div id="one" style="height: 300px;">第一</div>
<div id="two" style="height: 300px;">第二</div>
<a href='#one'>回到第一</a>
<a href='#two'>回到第二</a>
在vue项目中可能会导致第一次点击没有效果,第二次点击才跳到对应位置,
因为在 router中设置了 scrollBehavior: () => ({ y: 0 }),
导致的,但是我们需要路由跳转时滚动条回到初始位置,所以这里可以用另一种方法:即第二种
第二种:element.scrollIntoView()
实现 锚链接
<div id="one" style="height: 300px;">第一</div>
<div id="two" style="height: 300px;">第二</div>
<h2 @click="handleScroll('one')">回到第一</h2>
<h2 @click="handleScroll('two')">回到第二</h2>
methods: {
handleScroll(id) {
var element = document.getElementById(id);
element.scrollIntoView(); // 参数 false 代表 Bottom
}
}
页面滚动到顶部
document.documentElement.scrollTop = 0;