JS實現百分比水平條
阿新 • • 發佈:2019-02-14
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {margin:0;padding:0;}
.scroll {
width: 400px;
height: 8px;
background-color: #ccc;
margin: 100px;
position: relative;
border-radius: 4px;
}
.bar {
width: 10px;
height: 22px;
background-color: #369;
position: absolute;
top: -7px;
left: 0;
cursor: pointer;
border-radius: 4px;
}
.mask{
width: 0;
height: 100%;
background: #369;
border-radius: 4px 0 0 4px;
}
</style>
</head>
<body>
<div class="scroll" id="scroll">
<div class="bar"></div>
<div class="mask"></div>
</div>
<div id="demo"></div>
</body>
</html>
<script>
var scroll = document.getElementById("scroll");
var bar = scroll.children[0];
var mask = scroll.children[1];
var demo = document.getElementById("demo");
bar.onmousedown = function(event){
var that = this;
var event = event || window.event;
var left = event.clientX - this.offsetLeft;
document.onmousemove = function(event){
var event = event || window.event;
that.style.left = event.clientX - left + "px";
var val = parseInt(that.style.left);
if(val < 0){
that.style.left = 0;
} else if(val > 390){
that.style.left = "390px";
}
mask.style.width = that.style.left;
demo.innerHTML = parseInt(parseInt(that.style.left)/390*100)+"%";
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
</script>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {margin:0;padding:0;}
.scroll {
width: 400px;
height: 8px;
background-color: #ccc;
margin: 100px;
position: relative;
border-radius: 4px;
}
.bar {
width: 10px;
height: 22px;
background-color: #369;
position: absolute;
top: -7px;
left: 0;
cursor: pointer;
border-radius: 4px;
}
.mask{
width: 0;
height: 100%;
background: #369;
border-radius: 4px 0 0 4px;
}
</style>
</head>
<body>
<div class="scroll" id="scroll">
<div class="bar"></div>
<div class="mask"></div>
</div>
<div id="demo"></div>
</body>
</html>
<script>
var scroll = document.getElementById("scroll");
var bar = scroll.children[0];
var mask = scroll.children[1];
var demo = document.getElementById("demo");
bar.onmousedown = function(event){
var that = this;
var event = event || window.event;
var left = event.clientX - this.offsetLeft;
document.onmousemove = function(event){
var event = event || window.event;
that.style.left = event.clientX - left + "px";
var val = parseInt(that.style.left);
if(val < 0){
that.style.left = 0;
} else if(val > 390){
that.style.left = "390px";
}
mask.style.width = that.style.left;
demo.innerHTML = parseInt(parseInt(that.style.left)/390*100)+"%";
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); //防止選擇拖動,前者正常寫法,後者document.selection.empty()相容IE678寫法
}
document.onmouseup = function(){
document.onmousemove = null;
}
</script>