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


先看看大概效果

 

 

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

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

 

最后在自己想用的地方映入組件即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM