<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滑动条</title>
<style type="text/css">
.box{
400px;
height: 8px;
background-color: #ccc;
margin: 100px auto;
position: relative;
}
.box .bar{
10px;
height: 20px;
background-color: #369;
position: absolute;
top: -6px;
left: 0;
cursor: pointer;
}
.box .mask{
0px;
height: 100%;
background-color: #369;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="bar" id="bar"></div>
<div class="mask" id="mask"></div>
</div>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
var bar = $('bar');
//onclick事件,是鼠标点击下去,然后松开手才会触发
//onmousedown事件,是鼠标点击下去就触发
bar.onmousedown = function(event){
var evt = event || window.event;
var mLeft = evt.clientX - bar.offsetLeft;
document.onmousemove = function(event){
var evt = event || window.event;
var barX = evt.clientX - mLeft;
if(barX < 0){
barX = 0;
}
if(barX > (bar.parentNode.offsetWidth - bar.offsetWidth)){
barX = (bar.parentNode.offsetWidth - bar.offsetWidth)
}
bar.style.left = barX + 'px';
$('mask').style.width = barX + 'px';
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
//一定要在bar.onmousedown内部注册,否则不起作用
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
</body>
</html>