小程式播放當前視訊關閉其他視訊

Bright2017發表於2018-11-29
<view wx:for="{{courseList}}" wx:for-item="course" class='course-pannle-item' wx:for-index="idx">
  <view class='video-item'>
    <video wx:if='{{idx==playIndex}}' id='video{{idx}}' autoplay='{{true}}' show-center-play-btn="{{false}}" src='{{course.videoUrl}}' controls="true" objectFit="cover">
    </video>
    <image class='video-cover' wx:if='{{idx!=playIndex}}' mode='widthFix' src='{{course.coverUrl}}'></image>
    <image class='video-play-btn' wx:if='{{idx!=playIndex}}' mode='widthFix' data-index='{{idx}}' bindtap='videoPlay' src='/images/img11.png'></image>
    <text wx:if='{{idx!=playIndex}}' class='video-duration fs-28'>{{course.duration}}</text>
  </view>
</view>
.video-item{
  position: relative;
  width: 100%;
  height: 420rpx;
}
video{
  width: 100%;
  height: 100%;
}
.video-cover{
  position: absolute;
  left: 0;
  top: 0
}
.video-play-btn{
  position: absolute;
  width: 120rpx;
  height: 120rpx;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto
}
.video-duration{
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: #fff;
}
var app = getApp();


Page({

  /**
   * 頁面的初始資料
   */
  data: {
    playIndex: null,//用於記錄當前播放的視訊的索引值
    courseList: [{
      videoUrl: 'xxx.mp4',//視訊路徑
      coverUrl: '/images/img2.jpg', //視訊封面圖
      duration: '03:00', //視訊時長
    }, {
        videoUrl: 'xxx.mp4',
        coverUrl: '/images/img3.png',
      duration: '04:45',
    }]
  },
  videoPlay: function (e) {
    var curIdx = e.currentTarget.dataset.index;
    // 沒有播放時播放視訊
    if (!this.data.playIndex) {
      this.setData({
        playIndex: curIdx
      })
      var videoContext = wx.createVideoContext('video' + curIdx) //這裡對應的視訊id
      videoContext.play()
    } else { // 有播放時先將prev暫停,再播放當前點選的current
      var videoContextPrev = wx.createVideoContext('video' + this.data.playIndex)
      if (this.data.playIndex != curIdx) {
        videoContextPrev.pause()
      }
      this.setData({
        playIndex: curIdx
      })
      var videoContextCurrent = wx.createVideoContext('video' + curIdx)
      videoContextCurrent.play()
    }
  }
})

大佬部落格地址:http://www.cnblogs.com/sese/p/9353864.html

相關文章