微信小程序实现滚动视频自动播放(未优化)
先看看大概效果
![](https://img2020.cnblogs.com/blog/1518690/202009/1518690-20200910100331454-1981689905.gif)
1.首先需要了解微信API:
wx.createIntersectionObserver(Object component, Object options)
创建并返回一个 IntersectionObserver 对象实例。在自定义组件或包含自定义组件的页面中,应使用 this.createIntersectionObserver([options])
来代替
具体可以看微信小程序文档
2.由于我们这个区域是一个滚动区域,所以我用了scoll-view,最外层用scroll-view包裹
直接封装一个组件
player.js
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// pages/text/play.js const app = getApp() Component({ /** * 组件的属性列表 */ properties: { index: { type: Array, value: [] } }, ready() { }, attached() { // 获取随机数字 给video标签id命名 可使用时间戳 var random = Math.floor(Math.random() * 1000); // 全局获取 屏幕高度宽度 var { screenHeight, screenWidth } = app.globalData.systemInfo this.setData({ screenHeight, screenWidth, random }) var that = this var screenHeight = screenHeight //获取屏幕高度 var screenWidth = screenWidth //获取屏幕宽度 let topBottomPadding = screenHeight / 2 // 获取试图目标元素 const videoObserve = wx.createIntersectionObserver(this) // 设置试图可见区域 this.observe = videoObserve.relativeToViewport({ top: -topBottomPadding + 10, bottom: -topBottomPadding }) // // 暂存随机 var random = that.data.random this.observe.observe(`#vids${that.data.random}`, (res) => { let { intersectionRatio } = res // var videoNow = wx.createVideoContext(res.id,that) if (intersectionRatio > 0) { //离开视界,因为视窗占比>0,开始播放 // that.setData({ // playstart: true // }) //进入视界,开始播放 console.log('start',res); wx.createVideoContext(res.id,that).play() wx.createVideoContext('vids',that).play() // that.observe.disconnect() } else { // 离开试图 暂停播放 console.log('stop',res); wx.createVideoContext('vids',that).pause() wx.createVideoContext(res.id,that).pause() // that.observe.disconnect() // that.setData({ // playstart: false // }) } }) }, /** * 组件的初始数据 */ data: { list: [], playstart: false, screenHeight: "", screenWidth: "", random: '', }, /** * 组件的方法列表 */ onShow() { }, methods: { } })
player.wxml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<view class="box" hover-class="none"> <view class=""> <video class="vids" id="vids{{random}}" data-index='{{index}}' src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400"></video> </view> </view>
大概实现功能,可以自己设置
最后在自己想用的地方映入组件即可