三种方法

<div @click="go">点击下滑</div>
<div id="show" ref="view">展示</div>

1、利用scrollIntoView()方法,该方法将调用它的元素滚动到浏览器窗口的可见区域(根据其他元素的布局,元素可能无法完全滚动到顶部或底部)
ps:页面可滚动时才有用!!!可通过设置css实现

methods:{
    go(){
      document.getElementById("show").scrollIntoView();
      /*或
      document.querySelector("#idshow").scrollIntoView();
  	  或
  	  this.$refs.view.scrollIntoView();
  	  */
    }
  }

scrollIntoView提供了scrollIntoViewOptions对象参数

scrollIntoViewOptions定义过渡动画
behavior定义缓慢动画,可选值:auto、instant 或 smooth。默认为 auto
block定义垂直方向的对齐,可选值:start,center,end 或 nearest。默认为 center
inline定义水平方向的对齐,可选值:start,center,end 或 nearest。默认为 nearest

示例:缓慢移动至目标

 function Go () {
      document.getElementById('kinds').scrollIntoView({ behavior: 'smooth' })
    }

2、通过scrollTop设置滚动距离
(1)scrollTop=0,没有滚动
(2)scrollTop>0,有滚动距离,但没有滚动到底部
(3)scrollTop=scrollHeight-clientHeight,滚动到了底部

//监听scroll
this.$refs.wrapper.addEventListener('scroll', this.judgeScroll);

methods:{
	goAnchor(){
  		this.$refs.view.scrollTop = 距离
	}
}

3、使用a标签锚点
不适合在vue.js项目中使用,会干扰路由里的hash值

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐