11 - Custom Video Player

白彦
2023-12-01

11 - Custom Video Player

const player = document.querySelector('.player');
const video = player.querySelector('.viewer');
const toggle = player.querySelector('.toggle');
const skipButton = player.querySelectorAll('[data-skip]');
const ranges = player.querySelectorAll('.player__slider');
const progress = player.querySelector('.progress');
const progressBar = player.querySelector('.progress__filled');


function togglePlay(){
    // console.log(video.paused);
    const method = video.paused ? 'play' :'pause';
    video[method]();
    // if(video.paused){
    //     video.play();
    // }else{
    //     video.pause();
    // }
}
function buttonToggle(){
    const ico = video.paused ? '▶' :'||';
    toggle.textContent = ico;
}
function skip(){
    // console.log('skip……');
    console.log(this.dataset.skip);
    video.currentTime += parseFloat(this.dataset.skip);

}
function rangeHandle(){
    console.log(this.name);
    console.log(this.value);
    video[this.name] = this.value;
    // video.volume
}
function handleProgress() {
    const percent = (video.currentTime / video.duration) * 100;
    progressBar.style.flexBasis = `${percent}%`;
  }
function changeHandle(e){
    const clickSite = (e.offsetX / progress.offsetWidth) * video.duration;
    video.currentTime = clickSite;
// 自动触发进度条改变事件  
}

video.addEventListener('click',togglePlay);
video.addEventListener('play',buttonToggle);
video.addEventListener('pause',buttonToggle);
video.addEventListener('timeupdate', handleProgress);
toggle.addEventListener('click',togglePlay);
skipButton.forEach(skipBtn => skipBtn.addEventListener('click',skip));

ranges.forEach(range => range.addEventListener('mousemove',rangeHandle));
ranges.forEach(range => range.addEventListener('change',rangeHandle));
progress.addEventListener('click',changeHandle)

let mousedown = false;
progress.addEventListener('mousedown',()=>mousedown = true);
progress.addEventListener('mouseup',()=>mousedown = false);
progress.addEventListener('mousemove',(e)=>mousedown && changeHandle(e));

 类似资料: