<!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"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>鼠标拖拽,不能拖出指定对象,吸附作用(类似PS工具框)</title> <style> #div1{width: 100px;height: 100px;background: red;position: absolute;} #div2{width: 700px;height: 500px;background: #ccc;position: relative;margin:100px auto;} </style> <script> window.onload=function(){ var oDiv=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); var disX=0; var disY=0; oDiv.onmousedown=function(ev){ var oEvent=ev||event; disX=oEvent.clientX-oDiv.offsetLeft; disY=oEvent.clientY-oDiv.offsetTop; document.onmousemove=function(ev){ var oEvent=ev||event; var left=oEvent.clientX-disX; var top=oEvent.clientY-disY; var right=oDiv2.offsetWidth-oDiv.offsetWidth; var bottom=oDiv2.offsetHeight-oDiv.offsetHeight; //让div出不去浏览器 if(left<50){//吸附距离 left=0; }else if(left>right){ left=right; } if(top<50){ top=0; }else if(top>bottom){ top=bottom; } oDiv.style.left=left+'px'; oDiv.style.top=top+'px'; }; document.onmouseup=function(ev){ document.onmousemove=null; document.onmouseup=null; }; return false;//火狐阻止默认事件,不然会有bug,解决下面div一定要加内容的bug } } </script> </head> <body> <div id="div2"> <div id="div1"></div> </div> </body> </html>