要实现一个锚点定位的效果,传统方法是用 a 标签的 href 属性和 id 属性来做。
不过并不能达到想要的效果,在Vue项目中,使用传统的在a标签的href属性中写id的方法无效,会导致浏览器的地址改变从而跳转到其他页面。
vue-router 用的是 hash 模式,不能使用传统 a 标签的方式来做锚点定位。
经过各种百度,发现好多用的是以下方式,但是经过实测并没有用,没有实现定位。
(希望有大佬指导下)
document.body.scrollTop = this.$el.querySelector(selector).offsetTop
而后,发现 scrollIntoView()
方法,实测可用:
// document 和 this.$el 都可以
document.querySelector(selector).scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});
// 动画过渡效果-behavior: "auto" 或 "smooth" 默认为 "auto"
// 垂直方向对齐-block: "start", "center", "end", 或 "nearest" 默认为 "start&#