原理
鼠标事件原理加小遮罩
上代码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.scroll{
width: 400px;
height: 8px;
background-color: lightblue;
margin: 100px 0 10px 100px;
position: relative;
}
.bar{
width: 10px;
height: 20px;
position: relative;
top:-6px;
background-color: darkcyan;
}
.mask{
width: 0;
height: 100%;
position: absolute;
top:0;
background-color: mediumblue;
}
#demo{
margin-left: 100px;
}
</style>
</head>
<body>
<div class="scroll" id="scro">
<div class="bar" id="ba"></div>
<div class="mask"></div>
</div>
<div id="demo"></div>
</body>
</html>
<script>
var scro=document.getElementById("scro");
var ba=document.getElementById("ba");
var mask=scro.children[1];
var demo=document.getElementById("demo");
ba.onmousedown=function(event){
var event=event||window.event;
var leftval=event.clientX-this.offsetLeft;
// console.log(leftval);
var that=this;
document.onmousemove=function(event){
var event=event||window.event;
ba.style.left=event.clientX-leftval+"px";
// console.log(ba.offsetLeft+"一样吧")
console.log(ba.style.left);
var baa=parseInt(that.style.left);
if(baa<0){
that.style.left=0;
}else if(baa>390){
that.style.left="390px";
}
mask.style.width=that.style.left;
demo.innerHTML="已经走了:"+ parseInt(parseInt(that.style.left)/(scro.offsetWidth-ba.offsetWidth)*100)+"%";
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
}
document.onmouseup=function(){
document.onmousemove=null;
}
</script>