页内跳转,跨页跳转,函数跳转
1.页内跳转:在同一个页面进行跳转
<a href="#miao">去找喵星人</a>
<h3 id="miao">喵星人基地</h3>
这种方案也能实现回到顶部功能
2.从A页面跳到B页面的指定锚点
思路:将锚点值作为query属性,传给B页面,然后B页面再通过props的方式传给他的子组件,最后在子组件中使用代码进行锚点跳转
commentId:'', // 要定位的元素的ID
mounted () {
if (this.commentId) {
setTimeout(() => {
let target = document.getElementById(this.commentId);
if (target) {
// scrollIntoView:实现滚动到特定元素的效果
target.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'center',
});
}
},500)
}
},
scrollIntoView
scrollIntoView是一个DOM元素的方法,用于将元素滚动到浏览器窗口的可见区域内。
scrollIntoView方法可以接受一个参数对象,用于指定滚动的行为
behavior:用于指定滚动的动画效果,可以设置为auto、smooth、instant
- auto表示使用浏览器默认的滚动行为
- smooth表示使用平滑的滚动效果
- instant表示立即滚动到指定位置
block:用于指定滚动的垂直位置,可以设置为start、center、end
- start表示将元素滚动到可见区域的顶部
- center表示将元素滚动到可见区域的中间
- end表示将元素滚动到可见区域的底部
inline:用于指定滚动的水平位置,可以设置为start、center、end
- start表示将元素滚动到可见区域的左侧
- center表示将元素滚动到可见区域的中间
- end表示将元素滚动到可见区区域的右侧