<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> #demo{ width:400px; height:20px; background-color: gray; margin:100px; position: relative; } #demo #bar{ width:10px; height:40px; background-color:pink; position:absolute; top:-10px; left:0; } #demo #jindu{ width:0 height:40px; background-color:pink; position:absolute; top:-10px; left:0; } </style> </head> <body> <div id="demo"> <div id="bar"></div> <div id="jindu"></div> </div> <div id="wenzi"></div> </body> </html> <script> var demo=document.getElementById("demo"); var bar=document.getElementById("bar"); var jindu=document.getElementById("jindu"); var wenzi=document.getElementById("wenzi"); bar.onmousedown=function (event) //onmousedown當鼠標按下的時候 { var event=event||window.event; var leftval=event.clientX-demo.offsetLeft; //按下鼠標的時候,記錄bar相對demo移動的距離 //alert(leftval); document.onmousemove=function (event) //拖動原理,鼠標按下接着移動鼠標,拖動必定寫道按下里面 { var event=event||window.event; bar.style.left=event.clientX-demo.offsetLeft-leftval +"px";//bar移動的距離 if(parseInt(bar.style.left)<0) { bar.style.left=0; } if(parseInt(bar.style.left)>390) { bar.style.left=390+"px"; } jindu.style.left=bar.style.left; wenzi.innerHTML="已經拖動"+parseInt((parseInt(bar.style.left)/390 *100))+"%"; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//防止選擇拖動 } document.onmouseup=function () { document.onmousemove = null; //彈起鼠標不作任何操做 } } </script>