1. 程式人生 > >HTML5高階例項之video

HTML5高階例項之video

更新日期:2018年3月27日18:07:55

動態建立常規video

let userVideo = document.createElement('video');
document.body.appendChild(userVideo);
//屬性width height autoplay id type src,也可以通過userVideo.setAttribute('type','video/mp4');來設定
userVideo.width = 320;
userVideo.height = 240;
userVideo.autoplay = true;
userVideo.id = 'userVideo-2'
; userVideo.type = 'video/mp4'; userVideo.src = "http://60.210.16.52/videos/other/1.mp4";//瀏覽器只支援mp4 hls //userVideo.load(); //userVideo.play(); userVideo.oncanplaythrough = document.getElementById("userVideo-1").play();

動態建立id不重複的可控video

function createVideo(id,src,autoplay,controls){
        //判斷id是否重名
        if
(duplicationId(id)){ console.log('id 重名,無法建立!'); return null; } //建立video let customVideo = document.createElement('div');// customVideo.id = id; customVideo.src = src; customVideo.autoplay = autoplay; customVideo.controls = controls; customVideo.type = "video/mp4"
; return customVideo } function duplicationId(id){ let allEle = document.getElementsByTagName('video'); let idArr = []; for(let i=0,len=allEle.length;i<len;i++){ idArr.push(allEle[i].getAttribute('id')); } if(idArr.indexOf(id) !== -1){ console.log('duplication id') return true }else{ console.log('can set id') return false } } //新增video let a = createVideo('customVideo1',"http://60.210.16.52/videos/other/20180228/ee/6e/dd04b4c964066489cd90c04fe79a1339.mp4?dis_k=27b2ad2afe70203668d7ac0c1df14054a&dis_t=1522138750&dis_dz=CNC-QiYi&dis_st=46&src=iqiyi.com&uuid=ca6c0ef0-5ab9fe7e-89&z=zibo5_cnc&pv=0.2",true,true); if(a){ document.body.appendChild(a); a.addEventListener('play',function(){ console.log(a.getAttribute('id') + ' play'); }); //音訊/視訊已暫停 a.addEventListener('pause',function(){ console.log(a.getAttribute('id') + ' pause'); }); //播放結束 a.addEventListener('ended',function(){ console.log(a.getAttribute('id') + ' end'); }); } let b = createVideo('customVideo2',"http://60.210.16.52/videos/other/20180228/ee/6e/dd04b4c964066489cd90c04fe79a1339.mp4?dis_k=27b2ad2afe70203668d7ac0c1df14054a&dis_t=1522138750&dis_dz=CNC-QiYi&dis_st=46&src=iqiyi.com&uuid=ca6c0ef0-5ab9fe7e-89&z=zibo5_cnc&pv=0.2",true,true); if(b){ document.body.appendChild(b); //音訊/視訊已開始或不再暫停 b.addEventListener('play',function(){ console.log(b.getAttribute('id') + ' play'); }); //音訊/視訊已暫停 b.addEventListener('pause',function(){ console.log(b.getAttribute('id') + ' pause'); }); //播放結束 b.addEventListener('ended',function(){ console.log(b.getAttribute('id') + ' end'); }); }