0
点赞
收藏
分享

微信扫一扫

Vue监听窗口滚动事件

野见 2022-03-30 阅读 87

Vue监听窗口滚动事件

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

监听窗口滚动事件

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

mounted () {
	window.addEventListener('scroll', this.handleScroll)
  },
destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  },

处理函数

methods: {
	handleScroll () {
		// 元素到页面顶部的距离
		var el_topHeight = this.$refs.one_video.offsetTop
		// 元素的高度
		var el_Height = this.$refs.one_video.clientHeight
		// 可视区高度
		var clientHeight = document.documentElement.clientHeight
		// 页面被卷去的高度
		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
		if (clientHeight + scrollTop > el_topHeight && this.one_video_num === 0) {
			this.one_video_num += 1 // 播放次数
			this.$refs.one_video.play()
		}
		if (clientHeight + scrollTop < el_topHeight) {
			this.one_video_num = 0
		}
	},
},
举报

相关推荐

0 条评论