从home
页面 -链接- list
页面
第一步:在home页面用a标签设置锚链接
<a href="/list#Scientists">跳去列表页 科学家</a>
<a href="/list#Innovators">跳去列表页 创新者</a>
第二步:在list页面设置id属性
<p id="Scientists">
列表页科学家内容
...
</p>
<p id="Scientists">
列表页创新者内容
...
</p>
第三步:判断当前页面的 window.location.hash
(标签值
),如果有就执行方法goAnchor()
滚动到元素位置
mounted() {
if (window.location.hash) {
this.$nextTick(() => {
this.goAnchor(window.location.hash);
});
}
},
methods: {
goAnchor (selector) {
let anchor = this.$el.querySelector(selector)
document.body.scrollTop = anchor.offsetTop;
document.documentElement.scrollTop = anchor.offsetTop;
},
}