前言
随着HTML5技术的成熟,网页内嵌视频播放器已经成为提升用户体验的一个重要功能,自HTML5<vedio>标签的出现,为网页视频播放提供了一种更加高效、兼容性更加强大的解决方案。
实现效果
HTML
<div class="wrapper">用于创建一个包装器div元素,包含视频播放器及其控制组件。<vedio>元素中的src="./mv.mp4"指定了视频文件的路径,controls属性告诉浏览器显示默认的播放控制条,包括播放/暂停按钮、进度条等。<div class="speed">是视频速度的控制条,用来调整视频播放速度。<div class="speed-bar">1x</div>代表当前的速度设置,默认为1x。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>video</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="wrapper">
<video src="./mv.mp4" class="video" controls width="765" height="430"></video>
<div class="speed">
<div class="speed-bar">1x</div>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
CSS
*{
margin: 0;
padding: 0;
}
body{
background:#aaa;
}
.wrapper{
position: fixed;
left: 50%;/* 父容器宽度的50% */
top: 50%;
transform: translate(-50%,-50%);/*自身的50% */
display: flex;/*子容器默认同一行*/
}
.speed{
width: 50px;
height: 430px;
background-color: #fff;
border-radius: 50px;/*bdrs*/
overflow: hidden;
}
.speed-bar{
width: 100%;
height: 16%;
background:linear-gradient(to bottom,#c6ffdd,#fbd786,#f7797d);
display: flex;/*设置为弹性容器*/
justify-content: center;/*在主轴方向上居中*/
align-items: center;/*在副轴方向上居中*/
cursor: pointer;/*鼠标放上去为一个小手*/
}
JS
- 使用
document.querySelector方法来获取相应的类名。 - 使用
speed.addEventListener给速度控制条容器添加一个mousemove事件监听,即当鼠标在.speed范围内移动时,会触发相应的函数。 var y=e.pageY-speed.getBoundingClientRect().top;计算鼠标当前位置的Y坐标与速度条顶部的距离。var percent=y/speed.offsetHeight;根据鼠标位置计算鼠标在速度条中的相对位置的百分比。var height=Math.round(percent*100)+'%';计算并设置.speed-bar的高度,使其随着鼠标的移动而变化。speedBar.textContent=playSpeed.toFixed(2)+'x'; video.playbackRate=playSpeed;更新.speed-bar内的文本内容,显示当前的播放速度。
//获取白底容器
//在白色容器上监听鼠标的移动事件
//获取到鼠标移动的距离
//根据鼠标移动的距离来设计彩色容器的高度
var speed=document.querySelector('.speed');
var speedBar=document.querySelector('.speed-bar');
var video=document.querySelector('.video');
speed.addEventListener('mousemove',function(e){
var y=e.pageY-speed.getBoundingClientRect().top;
var percent=y/speed.offsetHeight;
var height=Math.round(percent*100)+'%';
//用js修改speed-bar容器的高度
speedBar.style.height=height;
var min=0.4;
var max=4;
var playSpeed=percent*(max-min)+min;
speedBar.textContent=playSpeed.toFixed(2)+'x';
video.playbackRate=playSpeed;
})