小程序接口实现点击当前video,暂停页面其它video
1.开发过程
1.1.使用接口
今日开发小程序时,需要点击当前video播放,其它video暂停。
下面来记录一下
首先我先在小程序开发文档中找了对应的 API , 找了半天发现了这个
下面也附上了此API获取实例中的一些方法
上面的实例的方法没有全部列出,大家可以到 小程序文档 中查看。
小程序有很多的接口,说明其实并不那么详细,所以说找接口时也浪费了很多时间。
附上代码
wxml代码:
js 代码:
onReady: function (res) { this.videoContext1 = wx.createVideoContext('1') this.videoContext2 = wx.createVideoContext('2') this.videoContext3 = wx.createVideoContext('3') this.videoContext4 = wx.createVideoContext('4') //创建wx.createVideoContext对象,有四个视频所以创建四个对象来控制视频 }, //控制除了点击之外的视频停止播放 //stop() 为 API 创建的对象中的方法 play1: function(enl){ this.videoContext2.stop() this.videoContext3.stop() this.videoContext4.stop() }, play2: function (enl) { this.videoContext1.stop() this.videoContext3.stop() this.videoContext4.stop() }, play3: function (enl) { this.videoContext2.stop() this.videoContext1.stop() this.videoContext4.stop() }, play4: function (enl) { this.videoContext2.stop() this.videoContext3.stop() this.videoContext1.stop() }到这里功能就已经实现了,但是事情还没完,真写成这样就太辣鸡了。
因为视频是后台数据传过来的,所以页面中可能不会只有4个视频,要是传过来10个视频怎么办呢,所以说我们要根据视频的数量来动态的实现这个功能。
于是开始重构代码
1.2.重构代码
html代码:
<block wx:for='{{video}}'> <video id='{{item.id}}' bindplay="play" src='{{item.url}}' poster='{{item.fm_logo}}' enable-progress-gesture='true'></video> </block> //修改了bindplay,不再定义四个事件函数js代码:
1.数据请求时遍历接口
写到这里,就可以实现我们的功能了。
1.3.注意
着重说一下上文渲染API的代码
for(var a = 1;a <= num; a++){ i[`videoContext${a}`] = wx.createVideoContext(`${a}`) }// i.videoContext1 = wx.createVideoContext('1') // i.videoContext2 = wx.createVideoContext('2')// i.videoContext3 = wx.createVideoContext('3')// i.videoContext4 = wx.createVideoContext('4')i[`videoContext${a}`] = wx.createVideoContext('' + a + '') // 正确i[`videoContext${a}`] = wx.createVideoContext(`${a}`) // 正确i[`videoContext${a}`] = wx.createVideoContext('`${a}`') // 错误i[`videoContext${a}`] = wx.createVideoContext("'" + a + "'") // 错误i.`videoContext${a}` = wx.createVideoContext('' + a + '') // 错误i.videoContext`${a}` = wx.createVideoContext('' + a + '') // 错误此处用到了ES6模板字符串以及对象的属性名表达式,也是之前的基础打的不够牢固,以至于这里卡了很久
2.总结
2.1.wx.createVideoContext( )
两个参数
第一个参数:组件的 id(必填)
第二个参数:在自定义组件情况下,当前组件实例的this,以操作组件内 video 组件
返回值
返回一个 VideoContext 对象
方法
见小程序文档
2.2.实现思路
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

