0
点赞
收藏
分享

微信扫一扫

页面滚动到指定位置

杨沐涵 2022-03-14 阅读 38

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>

1
2
3

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)
 }
       
举报

相关推荐

0 条评论