自定义播放控件
代码所需css文件
链接: https://pan.baidu.com/s/1UGu6z-KIsIe3UXHKV6Cbkg 提取码: 3qmb
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="./font/iconfont.css">
</head>
<body>
<div id="wrap">
<h2>视频播放器</h2>
<div class="player">
<i class='iconfont icon-jiazai wait'></i>
<video src="./video/1.mp4" ></video>
<div class="controls">
<a href="javascript:void(0);" class='pause switch iconfont icon-zanting1'></a>
<div class="progress">
<div class="line"></div>
<div class="bar"></div>
</div>
<div class="time">
<span class="current">00:00:00</span>/
<span class="total">00:00:00</span>
</div>
<a href="javascript:void(0)" class='full screen icon-Shapecopy iconfont'></a>
</div>
</div>
<script>
var $ = select=>document.querySelector(select)
//当视频加载完成
$('video').oncanplay = function(){
setTimeout(()=>{
//隐藏 加载动画
$('.wait').style.display = 'none'
//显示视频
this.style.display = 'block'
//设置视频的总时间
$('.total').innerText = handleTime(this.duration)
},2000)
}
//处理时间
function handleTime(time){
//1小时 = 3600s
var h = Math.floor(time/3600) ;//小时
var m = Math.floor(time%3600/60); //分钟
var s = Math.floor(time%60)
return toTwo(h)+':'+toTwo(m)+':'+toTwo(s)
}
//一位数字变成两位数字 1 --> 01
function toTwo(num){
return num<10?'0'+num:num;
}
//点击 暂停按钮
$('.pause').onclick = function () {
if(this.classList.contains('icon-zanting1')){
this.classList.remove('icon-zanting1')
this.classList.add('icon-zanting')
//播放视频
$('video').play()
}else{
this.classList.add('icon-zanting1')
this.classList.remove('icon-zanting')
//暂停视频
$('video').pause()
}
}
//当视频的currentTime属性变化时 触发回调函数
$('video').ontimeupdate = function(){
/*
* bar.width/line.width = this.currentTime/this.duration
* */
// var width = this.currentTime*$('.line').clientWidth/this.duration+'px';
var width = (this.currentTime/this.duration)*100+'%';
$('.bar').style.width = width;
//设置视频的播放时间
$('.current').innerText = handleTime(this.currentTime)
}
//把bar和line的点击事件委托给父元素 progress
$('.progress').onclick = function (e) {
console.log(e.target);
/*
* currentTime/duration = e.offsetX/line.width
* */
var currentTime = e.offsetX*$('video').duration/$('.line').clientWidth
$('video').currentTime = currentTime
}
//点击全屏按钮
$('.full').onclick = function () {
if(this.classList.contains('icon-Shapecopy')){
this.classList.remove('icon-Shapecopy')
this.classList.add('icon-tuichuzhuanhuan')
//让player全屏显示
$('.player').mozRequestFullScreen()
}else{
this.classList.add('icon-Shapecopy')
this.classList.remove('icon-tuichuzhuanhuan')
//退出全屏显示
document.mozCancelFullScreen()
}
}
//当视频播放结束时 触发
$('video').onended = function(){
//$('.current').innerText = '00:00:00';
console.log(this.currentTime);
//让视频的播放时间归零
this.currentTime = 0;
$('.pause').classList.add('icon-zanting1')
$('.pause').classList.remove('icon-zanting')
}
</script>
</div>
</body>
</html>