vue+js 实现鼠标滚轮滚动时,整页滚动效果

7 篇文章 0 订阅
  • 绑定滚轮事件,使滚轮滚动时停止页面滚动;同时记录浏览器高度。
data() {
      return {
      	pageHeight: 0,
      	scrollFLag: true,
	}
},
mounted() {
      window.addEventListener('mousewheel', this.mousewheelHandler, false)
      this.pageHeight = document.documentElement.clientHeight
},
  • 滚轮事件中获取滚轮走向,向上滚的话向上翻1页,向下滚的话向下翻1页。代码里加了粘滞,滚动3次时才翻页
mousewheelHandler(e){
        e.preventDefault()
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        if(delta > 0){
          this.wheelCount -= 1
        }else{
          this.wheelCount += 1
        }
        const scroll = document.documentElement.scrollTop
        const page = scroll/this.pageHeight + 1
        if(this.wheelCount == 3){
          this.nextPage(page+1, true)
        }else if(this.wheelCount == -3){
          this.nextPage(page-1, false)
        }
        if(this.wheelCount == 3 || this.wheelCount == -3){
          this.wheelCount = 0
        }
      },
  • 定义 scrollFLag 防止多次滚动,setTimeout清除flag;setInterval 使他平滑地滚,滚完后清除即可。
nextPage(page, isForward){
        if(this.scrollFLag){
          this.scrollFLag = false
          let scroll = document.documentElement.scrollTop
          const p = this.pageHeight*(page-1)
          let scrollTimer =  setInterval(()=> {
            isForward? scroll += navHeight: scroll -= navHeight
            if(isForward? scroll > p: scroll < p){
              clearInterval(scrollTimer)
            }
            document.documentElement.scrollTop = isForward? Math.min(scroll, p): Math.max(scroll, p)
          }, 20)
          setTimeout(()=>this.scrollFLag=true, 1200)
          // this.scrollFLag = true
        }
      },

用元素定位滚动位置会更准确,这里就不改了。小功告成。在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值