1. 程式人生 > 實用技巧 >微信小程式實現滾動視訊自動播放(未優化)

微信小程式實現滾動視訊自動播放(未優化)

先看看大概效果 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: { } })
View Code

player.wxml

<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>
View Code

大概實現功能,可以自己設定

最後在自己想用的地方映入元件即可