微信小程式實現滾動影片自動播放(未優化)
- 2020 年 9 月 9 日
- 筆記
先看看大概效果

1.首先需要了解微信API:
wx.createIntersectionObserver(Object component, Object options)
創建並返回一個 IntersectionObserver 對象實例。在自定義組件或包含自定義組件的頁面中,應使用 this.createIntersectionObserver([options]) 來代替
具體可以看微信小程式文檔
2.由於我們這個區域是一個滾動區域,所以我用了scoll-view,最外層用scroll-view包裹
直接封裝一個組件
player.js

// 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

<view class="box" hover-class="none">
<view class="">
<video class="vids" id="vids{{random}}" data-index='{{index}}' src="//wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400"></video>
</view>
</view>
大概實現功能,可以自己設置
最後在自己想用的地方映入組件即可