代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 400px;
height: 100px;
display: flex;
align-items: center;
text-align: center;
}
.box span{
width: 40px;
}
.box em{
width: 40px;
}
.bar{
width: 280px;
height: 20px;
background-color: cadetblue;
position: relative;
}
.bar p{
position: absolute;
margin: 0px;
height: 20px;
width: 10px;
background-color: chartreuse;
}
.bar i{
width: 15px;
height: 30px;
top:-5px;
position: absolute;
background-color: chocolate;
left: 0px;
/* opacity: 0.5; */
}
</style>
</head>
<body>
<div class="box">
<span>0%</span>
<em>0</em>
<div class="bar">
<p>
<i></i>
</p>
</div>
<em>100</em>
</div>
<script>
var ospan=document.querySelector("span");
var obar=document.querySelector(".bar");
var op=document.querySelector("p");
var oi=document.querySelector("i");
//包含快的宽度
var obarW=obar.offsetWidth;
//滑块的宽度
var oiW=oi.offsetWidth;
//1.鼠标摁下
oi.onmousedown=function(eve){
var e1=eve||window.event;
//2.鼠标移动 绑定在document身上
document.onmousemove=function(eve){
// console.log(1);
var e2=eve||window.event;
//3.确定鼠标移动的距离 可视区的坐标-鼠标摁下时的坐标-包含块的宽度
var l=e2.clientX-e1.offsetX-oi.offsetParent.offsetLeft;
//4.确定鼠标移动距离的范围 在一定范围内滑动,必然会有范围
if(l<0) l=0;
if(l>obarW-oiW) l=obarW-oiW;
oi.style.left=l+"px";
op.style.width=l+10+"px";
ospan.innerHTML=Math.round(l/(obarW-oiW)*100)+"%";
}
//5.鼠标抬起事件
document.onmouseup=function(){
//将鼠标按下事件清空
document.onmousedown=null;
//将鼠标移动清空
document.onmousemove=null;
}
//阻止默认事件
return false;
}
</script>
</body>
</html>