小程序实现一个页面多个视频点击一个视频只播放当前视频暂停其他视频

小程序实现一个页面多个视频点击一个视频只播放当前视频暂停其他视频,

在这里插入图片描述

第一种方法

下面是page的代码
//定义变量indexCurrent:null
 data:{
	  indexCurrent:null,
	}
video_play(e) {
    let curIdx = e.currentTarget.id;
    // 没有播放时播放视频
    console.log(curIdx)
    if (!this.data.indexCurrent) {
      this.setData({
        indexCurrent: curIdx
      })
      let videoContext = wx.createVideoContext(curIdx, this) //这里对应的视频id
      videoContext.play()
    } else { // 有播放时先将prev暂停,再播放当前点击的current
      /*this是在自定义组件下,当前组件实例的this,以操作组件内 video 组件(在自定义组件中药加上this,如果是普通页面即不需要加)*/
      let videoContextPrev = wx.createVideoContext(this.data.indexCurrent, this)
      if (this.data.indexCurrent != curIdx) {
        videoContextPrev.pause()
        this.setData({
          indexCurrent: curIdx
        })
        let videoContextCurrent = wx.createVideoContext(curIdx, this)
        videoContextCurrent.play()
      }
    }
  }
下面是wxml的代码
<!--视频列表区域-->
  <scroll-view scroll-y class="videoScroll">
    <view class="videoItem" wx:for="{{videoList}}" wx:key="id">
      <video enable-play-gesture id="video{{item.id}}" bindtap="videoPlay" src="{{item.url}}"></video>
    </view>
  </scroll-view>

第二种方法

下面是page的代码
let flag = false
page({
//点击播放/继续播放的回调
  handlePlay (event) {
    let vid = event.currentTarget.id
    //关闭上一个播放的视频
    this.vid !== vid && this.videoContext && this.videoContext.stop()

    //创建控制video标签的实例对象
    this.videoContext = wx.createVideoContext(vid)
    //判断视频video是否相同。如果不相同再判断flag,flag为true说明没有视频正在播放
    if (this.vid !== vid && !flag) {
      this.videoContext.play()
    }else {
      // this.videoContext.pause()
      if (flag) {
        this.videoContext.play()
        flag = false
      }else {
        this.videoContext.pause()
        flag = true
      }
    }
    this.vid = vid
  }
})
下面是wxml的代码
<!--视频列表区域-->
  <scroll-view scroll-y class="videoScroll">
    <view class="videoItem" wx:for="{{videoList}}" wx:key="id">
      <video enable-play-gesture id="video{{item.id}}" bindtap="handlePlay" src="{{item.url}}"></video>
    </view>
  </scroll-view>
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值