Vue锚链接(两种方法) scrollIntoView

第一种:常见 锚链接,idhref 结合起来
<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;

版权声明:本文为sunshineTing2原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。