视频方案
# 视频滑动自动播放
功能:视频滑动到当前视口内自动播放,划走自动停止
实现:传统的实现方法是,监听到 scroll 事件后,调用目标元素(绿色方块)的 getBoundingClientRect() 方法,得到它对应于视口左上角的坐标,再判断是否在视口之内。这种方法的缺点是,由于 scroll 事件密集发生,计算量很大,容易造成性能问题。目前有一个新的 IntersectionObserver API,可以自动"观察"元素是否可见,Chrome 51+ 已经支持。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做"交叉观察器"。
参考文档(https://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html)
html 代码
<video ref="scoll_player" :x-webkit-airplay="true" :x5-playsinline="true" :webkit-playsinline="true" playsinline preload="metadata" controlsList="nodownload" loop muted width="100%" height="100%" :poster="videoInfo.poster" > <source :src="videoInfo.videoUrl" /> </video>
js 代码
// 滚动播放 observerPlayer() { if (!IntersectionObserver) { console.log('浏览器不支持 IntersectionbserverAPI') return } this.observers = new IntersectionObserver( entries => { const entry = entries[0] // intersectionRatio 目标元素的可见比例 if ((entry?.intersectionRatio = 1)) { entry?.target?.play() } else { entry?.target?.pause() } }, { rootMargin: '0px', threshold: [0.8, 0.9, 1] } ) const targets = this.$refs?.scoll_player if (targets?.length) { targets.forEach(target => { this.observers.observe(target) }) } } // 销毁监听 unObserverPlayer(){ this.observers?.disconnect() }