幾種方法:
1.scrollIntoView()
<div ref="wrapper">
<div @click = goAnchor()></div>
<ul id="idName" ref="refName">
<li></li>
...
</ul>
</div>
goAnchor(){
document.getElementById("idName").scrollIntoView();
//或者
document.querySelector("#idName").scrollIntoView();
//或者
this.$refs.refName.scrollIntoView();
}
2.scrollTop = xxx
我知道有人會寫:
goAnchor(){
document.documentElement.scrollTop = distance
}
如果不是監聽window的scroll呢?那麼這樣寫其實是沒反應的。
這裡我對wrapper監聽scroll
this.$refs.wrapper.addEventListener('scroll', this.judgeScroll);
那麼最後的scrollTop就寫監聽滾動的對象的scrollTop
goAnchor(){
this.$refs.wrapper.scrollTop = xxx
}
3.使用a标簽錨點
不适合在vue.js項目中使用,會幹擾路由裡的hash值