<!DOCTYPE html>
<html lang="en">
<head>
<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>
* {
margin: 0;
padding: 0;
}
.box {
width: 800px;
height: 60px;
border: 1px solid;
margin: 300px auto;
}
.box .left {
margin-left: 20px;
margin-top: 10px;
width: 700px;
height: 40px;
background-color: #ccc;
border-radius: 10px;
float: left;
position: relative;
}
.box .right {
margin-top: 10px;
margin-left: 30px;
height: 40px;
line-height: 40px;
float: left;
}
.box .left .progressbar {
width: 30px;
height: 60px;
background-color: red;
position: absolute;
top: -10px;
left: 0px;
border-radius: 10px;
cursor: move;
}
.box .left .bg {
width: 0px;
height: 40px;
background-color: red;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
</style>
</head>
<body>
<div class="box">
<div class="left">
<div class="bg"></div>
<i class="progressbar"></i>
</div>
<div class="right">0%</div>
</div>
<script>
var progressbar = document.querySelector(".progressbar"); //获取元素
var bg = document.querySelector(".bg");
var num = document.querySelector(".right");
// console.log(progressbar,bg,num);
progressbar.onmousedown = function (event) {
var event = event || window.event;
var l = event.clientX - progressbar.offsetLeft;
document.onmousemove = function (event) {
var event = event || window.event;
var x = event.clientX - l;
if (x <= 0) {
x = 0;
} else if (x >= progressbar.parentNode.offsetWidth - progressbar.offsetWidth) {
x = progressbar.parentNode.offsetWidth - progressbar.offsetWidth;
}
progressbar.style.left = x + "px";
bg.style.width = x + "px";
num.innerHTML = parseInt(x / (progressbar.parentNode.offsetWidth - progressbar.offsetWidth) * 100) + "%"
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
return false;
}
</script>
</body>
</html>
效果图