html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
padding: 0;
margin: 0;
}
#progress {
width: 800px;
height: 40px;
line-height: 40px;
/*background: #e8e8e8;*/
margin: 100px auto;
position: relative;
}
#progress_bar {
width: 700px;
height: 100%;
background: #727272;
border-radius: 10px;
position: relative;
}
#progress_bar_fg {
width: 0px;
height: 100%;
background: #ff960d;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
span {
width: 25px;
height: 50px;
position: absolute;
top: -5px;
left: 0px;
border-radius: 10px;
background: orange;
}
#value {
position: absolute;
top: 0;
right: 0;
}
</style>
</head>
<body>
<div id="progress">
<div id="progress_bar">
<div id="progress_bar_fg"></div>
<span id="mask"></span>
</div>
<div id="value">0%</div>
</div>
<script src="index.js"></script>
</body>
</html>
js部分
window.onload = function() {
let bar = document.getElementById("progress_bar")
let fg = document.getElementById("progress_bar_fg")
let mask = document.getElementById("mask")
let value = document.getElementById("value")
//监听鼠标按下
mask.onmousedown = function(event) {
let e = event || window.event
//获取mask初始位置
// console.log(mask.offsetLeft);
// console.log(e.clientX);
let offsetleft = e.clientX - mask.offsetLeft
//console.log(offsetleft);
//监听鼠标移动(在按下事件内)
document.onmousemove = function() {
let e = window.event || arguments[0]
//获取鼠标移动距离
let x = e.clientX - offsetleft
//mask移动
if (x < 0) {
x = 0
} else if (x >= bar.offsetWidth - mask.offsetWidth) {
x = bar.offsetWidth - mask.offsetWidth
}
mask.style.left = x + "px"
fg.style.width = x + "px"
value.innerText = parseInt(x / (bar.offsetWidth - mask.offsetWidth) * 100) + "%"
return false
}
//监听鼠标抬起(也在鼠标按下事件)
document.onmouseup = function() {
//销毁移动事件
document.onmousemove = null
}
}
}