用原生js实现的一个进度拖拽的效果,这个效果典型的应用就是调节音量。
本程序代码简单易懂,单页面可多次调用,效果如下图:
js进度拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js实现进度拖拽的效果</title>
<style>
body{margin:0;padding:0;font-size:12px;}
.scale{background: #ddd; width: 200px; height: 3px; position: relative;margin: 20px;}
.scale span{background:#aaa;width:8px;height:16px;position:absolute;left:-2px;top:-6px;cursor:pointer; border-radius: 3px;}
.scale div{background: #66D9EF; position: absolute; height: 3px; width: 0; left: 0; bottom: 0; }
</style>
</head>
<body>
<div class="scale" id="bar">
<div></div>
<span id="btn"></span>
</div>
音量:<span id="title">0</span>
<script>
var scale = function (btn,bar,title){
this.btn = document.getElementById(btn);
this.bar = document.getElementById(bar);
this.title = document.getElementById(title);
this.step = this.bar.getElementsByTagName("div")[0];
this.init = function (){
var f=this,g=document,b=window,m=Math;
f.btn.onmousedown=function (e){
var x=(e||b.event).clientX;
var l=this.offsetLeft;
var max=f.bar.offsetWidth-this.offsetWidth;
g.onmousemove=function (e){
var thisX=(e||b.event).clientX;
var to=m.min(max,m.max(-2,l+(thisX-x)));
f.btn.style.left=to+'px';
f.ondrag(m.round(m.max(0,to/max)*100),to);
b.getSelection ? b.getSelection().removeAllRanges() : g.selection.empty();
};
g.onmouseup=new Function('this.onmousemove=null');
};
};
this.ondrag = function (pos,x){
this.step.style.width=Math.max(0,x)+'px';
this.title.innerHTML=pos+'%';
};
this.init();
}
new scale('btn','bar','title'); //实例化一个拖拽
</script>
</body>
</html>
新建一个html文件,然后复制该段代码保存,用浏览器打开就能看到进度拖拽的效果了。