主要JS邏輯
function handleImgVideoUrl(curr,srcUrl,imgsAndVideos) { // 設置圖片和視頻播放 var vList = []; for (let index = 0; index < imgsAndVideos.length; index++) { vList.push( srcUrl + imgsAndVideos[index]); } var myvideo = document.getElementById("videoView"); var vLen = vList.length; if (vList[curr].indexOf('V_') >= 0) { $("#imgView").hide(); $("#videoView").show(); let url = vList[curr]; $('#videoView').attr('src', url); // myvideo.muted=true; curr++; if (curr >= vLen) { curr = 0; //重新循環播放 } myvideo.load(); myvideo.play(); } else { let url = vList[curr]; $("#videoView").hide(); $("#imgView").show(); $("#imgView").attr("src", url); curr++; if (curr >= vLen) { curr = 0; //重新循環播放 } setTimeout(function () { handleImgVideoUrl(curr,srcUrl,imgsAndVideos); }, 5000); } //視頻播放完執行的方法 myvideo.onended = function () { if (vList[curr].indexOf('V_') >= 0) { $("#imgView").hide(); $("#videoView").show(); let url = vList[curr]; $('#videoView').attr('src', url); // myvideo.muted=true; myvideo.load(); myvideo.play(); curr++; if (curr >= vLen) { curr = 0; //重新循環播放 } handleImgVideoUrl(curr, srcUrl,imgsAndVideos); } else { // 圖片 let url = vList[curr]; $("#videoView").hide(); $("#imgView").show(); $("#imgView").attr("src", url); curr++; if (curr >= vLen) { curr = 0; //重新循環播放 } setTimeout(function () { handleImgVideoUrl(curr, srcUrl,imgsAndVideos); }, 5000); } }; }
調用方法 其中 srcUrl為統一的路徑信息,VIArray為圖片和視頻的名稱數組(帶后綴)
var curr = 0; handleImgVideoUrl(curr,srcUrl, VIArray);
html 顯示
<img id="imgView" class="thumbnail" /> <video id="videoView" src="" autoplay="autoplay" muted="muted" style="width:100%; height:auto"></video>