js完美实现鼠标拖拽
程序代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www."> <html xmlns="http://www." > <head> <title>无标题页</title> <script type="text/javascript"> var X,Y; function tuo(event){ var e=event||window.event; X=e.clientX; Y=e.clientY; document.getElementById("xx").setAttribute("able",true);//自定义属性,用于是否可以拖拽 document.getElementById("xx").setAttribute("onmouseup","_tuo();"); //注册鼠标放开事件 document.getElementById("xx").setAttribute("onmousemove","test(event)"); //注册鼠标移动事件 document.getElementById("xx").setAttribute("onmousedown",""); //移除mousedown事件,防止在拖拽时一直执行 document.getElementById("x").value=X; document.getElementById("y").value=Y; } function _tuo(){ document.getElementById("xx").setAttribute("able",false); document.getElementById("xx").setAttribute("onmousemove",""); setTimeout("document.getElementById('xx').setAttribute('onmousedown','tuo(event)');",100);//防止在放开鼠标时因鼠标抖动而导致执行了mousedown事件,所以要延时开放 document.getElementById("x").value="x"; document.getElementById("y").value="y"; } function test(event){ var e=event||window.event; if(document.getElementById("xx").attributes["able"].nodeValue){ //必须在可拖拽的状态才执行拖拽 document.getElementById("xx").style.left = document.getElementById("xx").offsetLeft+(e.clientX-X); document.getElementById("xx").style.top = document.getElementById("xx").offsetTop+(e.clientY-Y); document.getElementById("k").value=e.clientX; } X=e.clientX; Y=e.clientY; document.getElementById("x").value=X; document.getElementById("y").value=Y; } </script> </head> <body> <div style="position:absolute; width:100%; height:100%; left:0px; top:0px;"> <div id="xx" style="position:absolute; width:100px; height:100px; top:100px; left:100px; background-color:Gray;" onmousedown="tuo(event);" onmouseout="_tuo(event);"> </div> <input type="text" id="x" value="x" /> <input type="text" id="y" value="y" /> <input type="text" id="k" value="k" /> </div> </body> </html>
[ 本帖最后由 awl805 于 2012-12-21 22:34 编辑 ]