需求:点击跳转到页面指定位置

<div >点击跳转到此处</div>

【法一】:

利用a标签的锚点跳转

<a href="#test">点击跳转</a>
由于锚点跳的原理是改变哈希值,所以会改变url
 
【法二】:
用js的scrollIntoView方法
document.getElementById('test').scrollIntoView()
此方法可以让当前的元素滚动到浏览器窗口的可视区域内,不会改变url,但会有兼容问题
 
【法三】:(推荐)
获取id为test的元素距离父元素顶部的位置,即offsetTop, 改变父元素的scrollTop (父元素有定位,可滚动)
document.querySelector('.scrollElement').scrollTop = document.getElementById('test').offsetTop;

 在vue中,demo示例

<button @click="jump(index)">点击</button>

<div ref="docs">
    <div >跳转到此处</div>
</div>

methods: {
    jump(id) {
        this.$refs.docs.scrollTop =  this.$el.querySelector(`#data-${id}`).offsetTop ;
    },
}    

 

相关文章:

  • 2021-11-06
  • 2021-09-08
  • 2021-12-10
  • 2021-07-05
  • 2021-08-06
  • 2021-09-19
  • 2019-03-29
  • 2021-11-29
猜你喜欢
  • 2021-12-31
  • 2021-12-31
  • 2022-01-01
  • 2021-11-30
  • 2021-11-06
  • 2021-11-06
  • 2021-11-06
相关资源
相似解决方案