直接粘贴到编辑器运行即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
.progress{
margin: 100px auto;
position: relative;
width: 300px;
height: 20px;
background-color: #e8e8e8;
border-radius: 10px;
display: flex;
}
.progress .left{
background-color: red;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
width: 0;
height: 20px;
}
.progress .bar{
background-color: blue;
width: 20px;
height: 30px;
border-radius: 4px;
margin-top: -5px;
position: absolute;
left: 0;
top: 0;
}
.progress .right{
position: absolute;
left: 310px;
top: 0;
}
</style>
</head>
<body>
<div class="progress">
<div class="left"></div>
<div class="bar"></div>
<div class="right">0%</div>
</div>
<script>
let progress = document.querySelector('.progress')
let left = document.querySelector('.left')
let bar = document.querySelector('.bar')
let right = document.querySelector('.right')
progress.onclick = function(eve) {
let e = eve || window.event
if(e.target.className === 'bar') return
let moveX = e.clientX - progress.offsetLeft
if(moveX >= progress.clientWidth - bar.clientWidth){
moveX = progress.clientWidth - bar.clientWidth
}
// 追加
left.style.width = moveX + 'px'
bar.style.left = moveX + 'px'
right.innerText = Number((moveX / (progress.offsetWidth - bar.offsetWidth) * 100).toFixed(2)) + '%'
}
bar.onmousedown = function(eve) {
let e = eve || window.event
// 获取元素距离左边的距离
let lf = e.clientX - bar.offsetLeft
document.onmousemove = (eve) => {
let e = eve || window.event
// 鼠标移动的距离
let moveX = e.clientX - lf
// 移动处理
if(moveX <= 0) {
moveX = 0
} else if(moveX >= (progress.offsetWidth - bar.offsetWidth)) {
moveX = progress.offsetWidth - bar.offsetWidth
}
// 赋值
left.style.width = moveX + 'px'
bar.style.left = moveX + 'px'
right.innerText = Number((moveX / (progress.offsetWidth - bar.offsetWidth) * 100).toFixed(2)) + '%'
// 清空事件
document.onmouseup = function() {
document.onmousemove = null
document.onmouseup = null
}
}
}
</script>
</body>
</html>