在Vue中,有三种方式可以实现H5页面滑动至指定位置

方法1:

//先获取目标位置距离
mounted() {
  this.$nextTick(() => {
     setTimeout(() => {
        let targetbox= document.getElementById('targetbox');
        this.target= targetbox.offsetTop;        
   })
  })
}
//再滑动指定距离
document.body.scrollTop = this.target;

方法2:

this.$nextTick(() => {
     this.$refs.DOM.scrollTo(0,200);
})

方法3:

document.getElementById("target").scrollIntoView();

避坑指南:

方法1,滑动至的元素不能是display:none,存在兼容问题,亲测在部分ios机子上document.body.scrollTop滑动无效。

方法2,未亲测过,但在this.$nextTick(()里执行滑动,感觉有点麻烦。

方法3,亲测可用,ios和android都可。只是要注意,如果页面有监听scroll事件,scrollIntoView也会触发scroll事件的。

Logo

前往低代码交流专区

更多推荐