Custom HTML5 Video Player
Step 1. HTML
Strep 2. 將需要使用的元件利用selectquery選取出來
Strep 3. 播放與暫停:togglePlay()
function togglePlay(){
// if(video.paused){
// video.play();
// }else{
// video.pause();
// }
//可簡寫成以下:
const method = video.paused?'play':'pause';
video[method]();
}
video.addEventListener('click,togglePlay');//點擊影片
toggle.addEventListener('click,togglePlay');//點擊播放暫停元件
Step 4. 更換播放暫停元件圖示/文字:updateButton()
function updateButton(){
const icon = this.paused ? '▶' :'❚ ❚';
toggle.textContent = icon;
}
video.addEventListener('play,updateButton');
video.addEventListener('pause,updateButton');
Step 5. 快轉:skip()
於html設定[data-skip],可在需要調整設定時於html直接調整
function skip(){
//該元件data中的[data-skip]字串
//console.log(this.dataset.skip);
video.currentTime += parseFloat(this.dataset.skip);
}
skipButtons.forEach(button=>button.addEventListener('click',skip)); //console.log(this.dataset.skip);
video.currentTime += parseFloat(this.dataset.skip);
}
skipButtons.forEach(button=>button.addEventListener('click',skip));
Step 6. 控制影片音量及播放速度:handleRangeUpdate()
於html使用input製作,class命名為 range 並設定 min 及 max 值
function handleRangeUpdate(){
video[this.name]=this.value;
//this.name 為 volume 或 rate
}
ranges.forEach(range=>
range.addEventListener('change',handleRangeUpdate))
ranges.forEach(range=>
range.addEventListener('mousemove',handleRangeUpdate))
Step 7. 播放bar隨著影片時間變更顏色:handleProgress()
function handleProgress(){
const percent = (video.currentTime / video.duration)*100;
progressBar.style.flexBasis = `${percent}%`;
}
video.addEventListener('timeupdate',handleProgress);
💫延伸資料:
- flex-basis — CSS: Cascading Style Sheets | MDN :使用flex的屬性修改呈現的比例。
- HTMLMediaElement: timeupdate — Web API 接口参考 | MDN
Step 8. 拖曳播放bar控制影片時間:scrub()
function scrub(e){
const scrubTime =
(e.offsetX/progress.offsetWidth)*video.duration;
video.currentTime=scrubTime;
}
let mousedown = false;
progress.addEventListener('click',scrub);
progress.addEventListener('mousemove',(e) =>
mousedown && scrub(e));
//如果 mousedown==true 就執行 scrub(e)
progress.addEventListener('mousedown',() => mousedown=true);
progress.addEventListener('mouseup',() => mousedown=false);
💫延伸資料: