H5之随机切换小视频

给 video 标签的 src 设置随机url地址

var videoList = [
    "http://1570433780207_9396.mp4",
    ...
    'xxx.mp4'
  ];
  
  // 获取视频
  function autoVideo() {

    // 随机获取一条视频数据
    var rand = Math.floor(Math.random() * videoList.length + 1) - 1;
    console.log(rand, 'rand')
    var randIndex = videoList[rand];
    console.log(randIndex)

    // 绑定的数据
    var str = '';
    var url = randIndex;
    str +=
      '<video id="video" autoplay="autoplay" controls="controls" x5-video-player-type="h5" x5-video-player-fullscreen="true" style="object-fit:fill">'
    str += '<source src="' + url + '" type="video/mp4">'
    str += '</source>'
    str += '</video>'
    $('.videoBox').html(str)
  };
  autoVideo()
  
  //播放完毕继续播放下一条
  window.video.onended = function () {
    var rand = Math.floor(Math.random() * videoList.length + 1) - 1;
    var randIndex = videoList[rand];
    console.log(randIndex, 'randIndex')
    //监听video.onended 视频播放完,随机绑定新的src连接,播放下一条视频
    this.src = randIndex;
  }
复制代码

给 img 标签加随机背景图片,刷新页面随机切换背景图片

<style>
        .wrap {
          width: 100%;
          height: 13.34rem;
          font-size: 0.3rem;
          background-color: #ffe8bc;
          color: #875a5a;
          margin: auto;
          text-align: center;
        }

        .wrap .randomImg {
          width: 100%;
          height: 10rem;
        }
    </style>
    
    <body>
        <div class="wrap">
            <!--设置随机背景图片-->
            <div class="randomImg" id="randomImg"></div>
        </div>
    </body>
    
    <script>
        bgImg = new Array(2);
        bgImg[0] = '../img/1.png';
        bgImg[1] = '../img/2.png';
        bgImg[2] = '../img/3.png';
        bgImg[3] = '../img/4.png';
        index = Math.floor(Math.random() * bgImg.length);
        $('.randomImg').css('background', 'url(' + bgImg[index] + ')');
        $('.randomImg').css('backgroundSize', 'cover');
    </script>
    
复制代码
相关文章
相关标签/搜索