vue右边导航栏回到顶部,且向上按钮的显示与隐藏

效果图如下:

在这里插入图片描述
在这里插入图片描述
然后直接看代码:

前端代码

<!-- 回顶部按钮为一张50*50的图片 -->
<!-- btnFlag 控制图片显示隐藏 -->
<!-- backTop 回顶部的方法 -->
<img v-if="btnFlag" class="go-top" src="图片url" @click="backTop">

css 代码

img{
	position: fixed;
	z-index: 99;
	right: 0;
	bottom: 50px;
	margin-bottom: 50px;
}

vue 代码

// vue的两个生命钩子,这里不多解释。
// window对象,所有浏览器都支持window对象。它表示浏览器窗口,监听滚动事件

<script>
	export default {
		data () {
			
		    return {
		      //v-if为true显示,false消失
			  btnFlag:true,
			  //记录屏幕滑动的值
		      scrollTop: 0
		    }
		  },
		
		// vue的两个生命钩子,这里不多解释。
		// window对象,所有浏览器都支持window对象。它表示浏览器窗口,监听滚动事件
		mounted:function(){
		  window.addEventListener('scroll', this.scrollToTop);
		  console.log(this.scrollToTop)
		},
		destroyed:function(){
		  window.removeEventListener('scroll', this.scrollToTop)
		},
		 
		 
		methods: {
		  // 点击图片回到顶部方法,加计时器是为了过渡顺滑
		  
		  backTop(){
		      const that = this;
		      let timer = setInterval(() => {
		        let ispeed = Math.floor(-that.scrollTop / 5)
		        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
		        if (that.scrollTop === 0) {
		          clearInterval(timer)
		        }
		      }, 16)
		  },
		 
		  // 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏
		  scrollToTop () {
		    const that = this
		    let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
		    that.scrollTop = scrollTop
		    if (that.scrollTop > 60) {
		      that.btnFlag = true
		    } else {
		      that.btnFlag = false
		    }
		  }
		},	
	}
</script>

该代码可以直接运行,只需套用到你现有代码即可。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值