下面不使用<video>的controls属性,通过创建一个自定义播放器演示如何使用js操作<video>元素。
效果图如下:
实现功能如下:
(1)可以播放,暂停,停止视频。
(2)可以改变播放速度(2倍速度加速播放,一半的速度慢速播放,正常速度播放)
(3)播放时有进度条,同时还能显示已播放时间。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
<!DOCTYPE html>
<html>
<head>
<meta charset=
"utf-8"
>
<title>hangge.com</title>
</head>
<style>
#durationBar{
border:solid 1px
#164900;
width:100%;
margin-bottom:5px;
}
#positionBar{
height:20px;
color:white;
font-weight:bold;
background:
#2D9900;
text-align:center;
}
</style>
<script>
//播放
function
play(){
var
video = document.getElementById(
"videoPlayer"
);
video.play();
}
//暂停
function
pause(){
var
video = document.getElementById(
"videoPlayer"
);
video.pause();
}
//停止
function
stop(){
var
video = document.getElementById(
"videoPlayer"
);
video.pause();
video.currentTime = 0;
}
//快放
function
speedUp(){
var
video = document.getElementById(
"videoPlayer"
);
video.play();
video.playbackRate = 2;
}
//慢放
function
slowDown(){
var
video = document.getElementById(
"videoPlayer"
);
video.play();
video.playbackRate = 0.5;
}
//正常速度
function
normalSpeed(){
var
video = document.getElementById(
"videoPlayer"
);
video.play();
video.playbackRate = 1;
}
//进度条相关
function
progressUpdate(){
var
video = document.getElementById(
"videoPlayer"
);
//动态设置进度条
var
postionBar = document.getElementById(
"positionBar"
);
postionBar.style.width = (video.currentTime / video.duration * 100) +
"%"
;
//设置播放时间
displayStatus.innerHTML = (Math.round(video.currentTime*100)/100) +
"秒"
;
}
</script>
<body>
<video id=
"videoPlayer"
src=
"hangge.mp4"
width=
"400"
height=
"300"
ontimeupdate=
"progressUpdate()"
>
</video>
<div id=
"durationBar"
>
<div id=
"positionBar"
><span id=
"displayStatus"
>0秒</span></div>
</div>
<button onclick=
"play()"
>播放</button>
<button onclick=
"pause()"
>暂停</button>
<button onclick=
"stop()"
>停止</button>
<button onclick=
"speedUp()"
>快放</button>
<button onclick=
"slowDown()"
>慢放</button>
<button onclick=
"normalSpeed()"
>正常</button>
</body>
</html>
|
来源:oschina
链接:https://my.oschina.net/jack088/blog/3178384