vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue点击滑动到页面指定位置

Vue之点击滑动到页面指定位置方式(点击下滑滚动)

作者:麻辣翅尖

本文详细介绍了利用scrollIntoView()方法、scrollTop属性及a标签锚点三种方法实现页面滚动操作,特别强调了scrollIntoViewOptions参数的使用,适合前端开发者参考

三种方法

<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值

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文