js实现鼠标拖拽效果
html代码部分:
<html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="css.css" /> <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script> </head> <body> <div id="draw"></div> </body> </html> <script src="js.js"></script>
css代码部分:
#draw{ width:50px; height:50px; border:2px solid #ccc; position:absolute; top:10px; left:10px; cursor:pointer; }
js实现代码:
var oDiv=document.getElementById("draw"); var x,y,xw,yw; oDiv.onmousedown=function(ev){ e=event || ev; x=e.clientX; y=e.clientY; xw=y-oDiv.offsetTop; // 初始y点距上边框的距离 yw=x-oDiv.offsetLeft; //初始x点距左边框的距离 document.onmousemove=function(ev){ e=event || ev; if(e.clientY<=0 && e.clientX>0){ oDiv.style.left=e.clientX-yw+"px"; oDiv.style.top="0px"; }else if(e.clientY>0 && e.clientX<=0){ oDiv.style.left="0px"; oDiv.style.top=e.clientY-xw+"px"; }else{ oDiv.style.left=e.clientX-yw+"px"; oDiv.style.top=e.clientY-xw+"px"; } }; } document.onmouseup=function(event){ e=event || ev; document.onmousemove=null; };
计算思路如下图:
首页要获初次点击时的坐标的 如(x,y),然后再根据x,y,oDiv.offsetTop,oDiv.offsetLeft计算出 初次点时 鼠标在框体的位置,从而得出移动后的盒子位置应为onmouseup的鼠标点-对应的距盒子顶部左边的距离。