Vue监听窗口滚动事件

例子:当video滚动到可视区时自动播放

所需数据

data () {
    return {
      window_height: null, // 浏览器可见区域高度
      scrollTop: null, // 页面被卷去的高度
      My_video_top: null, // 目标元素到顶部的高度
      My_video_Height: null, // 目标元素的高度
      allow_play: true, // 允许播放标志位
      playing: false, // 播放节流标志位
    }
  },

获取数据、监听窗口滚动事件

记得在恰当的地方清除事件监听

  mounted () {
    // 获取浏览器可见区域高度
    this.window_height = document.documentElement.clientHeight
    // 用户手动修改浏览器可见区域高度时修改变量
    window.addEventListener('resize', this.getWindowHeight)
    // 获取目标元素距离顶部高度
    this.My_video_top = this.$refs.vedio_kind.offsetTop
    // 获取目标元素高度
    this.My_video_Height = this.$refs.vedio_kind.offsetHeight
    // 窗口滚动监听
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
    window.removeEventListener('resize', this.getWindowHeight)
  },

处理函数

  methods: {
    getWindowHeight () {
      this.window_height = document.documentElement.clientHeight
    },
    handleScroll () {
      // 获取页面被卷去的高度
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (this.scrollTop + this.window_height > this.My_video_top && this.My_video_top + this.My_video_Height > this.scrollTop) {
        if (!this.playing && this.allow_play) {
          this.playing = true
          this.allow_play = false
          this.$refs.vedio_kind.play()
          this.playing = false
        }
      } else if (this.My_video_top + this.My_video_Height < this.scrollTop) { // 上滑不可见时,允许下次播放
        this.allow_play = true;
      } else if (this.My_video_top > this.scrollTop) { // 下滑不可见时,允许下次播放
        this.allow_play = true;
      }
    },
  },
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值