<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{width:600px;height:200px;border: solid 1px black;margin: 0 auto;display: flex;text-align: center;align-items: center;}
.box span{width:40px;line-height:40px;}
.box em{width:40px;line-height:40px;}
.bar{width:480px;background: #ccc;height:40px;position: relative;}
.bar p{margin: 0;height:40px;width:10px;background: red;}
.bar i{width:20px;height:60px;position: absolute;left:0px;top:-10px;background: blue;border-radius: 10px;}
</style>
<div class="box">
<span>0%</span>
<em>0</em>
<div class="bar">
<p><i></i></p>
</div>
<em>100</em>
</div>
var oi = document.querySelector(".bar i");
var op = document.querySelector(".bar p");
var ospan = document.querySelector(".box span");
var obar = document.querySelector(".bar");
oi.addEventListener("mousedown",function(eve){
// 按下时获取按下的事件对象,准备稍后获取按下时的坐标
var e1 = eve || window.event;
document.addEventListener("mousemove",move);
function move(eve){
var e2 = eve || window.event;
// 移动时利用鼠标相对于屏幕的坐标,减去,按下时的坐标,减去,所在框的距离坐标屏幕的距离
var l = e2.clientX - e1.offsetX - obar.offsetLeft;
// 边界限定
if(l<0) l=0;
if(l > obar.offsetWidth - oi.offsetWidth){
l = obar.offsetWidth - oi.offsetWidth
}
// 生效滑块
oi.style.left = l + "px";
// 生效进度条
op.style.width = l + 10 + "px";
// 计算比例
ospan.innerHTML = parseInt((l / (obar.offsetWidth - oi.offsetWidth)) * 100) + "%";
}
document.addEventListener("mouseup",up);
function up(){
document.removeEventListener("mousemove",move);
document.removeEventListener("mouseup",up);
}
// 阻止默认事件,防止选中文字
// return false;
e1.preventDefault();
})