1.锚点链接
<a href='#one'>1</a>
<a href='#two'>2</a>
<a href='#three'>3</a>
<h3 id="one">tag1</h3>
<h3 id="two">tag2</h3>
<h3 id="three">tag3</h3>
tag1
tag2
tag3
点击a标签,跳转到指定的位置,但是url后会加入相应的链接‘#one’,不利于单页面应用的后退
2.获取元素位置去滚动
tag1
tag2
tag3
点击测试
//获取指定元素到页面顶部的距离
getTop(el) {
let top = el.offsetTop
let parent = el.offsetParent
while (parent !== null) {
top += parent.offsetTop
parent = parent.offsetParent
}
return top
}
//滚动到该元素
goTag(){
let el = document.querySelector(`#one`)
let _height = this.getTop(el)
window.scrollTo(0, _height)
}