<!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> *{ margin: 0px; padding:0px; } #div1{ width: 500px; height: 500px; position: relative; border:1px solid #ff00ff; top:100px; left: 300px; } #div2{ position: absolute; width: 150px; height: 150px; top:0px; left:0px; background: #ff00ff; } .boxs{ border:1px dashed #000000; position: absolute; } </style> <script> function getpos(ev){ var scrolltop=document.documentElement.scrollTop||document.body.scrollTop; var scrollleft=document.documentElement.scrollLeft||document.body.scrollLeft; return {x:ev.clientX+scrollleft,y:ev.clientY+scrolltop} } function addEvent(obj,even,fn){ /*事件绑定*/ return obj.addEventListener?obj.addEventListener(even,fn,false):obj.attachEvent("on"+even,fn); } function unEvent(obj,even,fn){ return obj.removeEventListener?obj.removeEventListener(even,fn,false):obj.detachEvent("on"+even,fn); } window.onload=function(){ var odiv1=document.getElementById("div1"); odiv2=document.getElementById("div2"); disX=0; disY=0; addEvent(odiv2,"mousedown",function(ev){ var eventr=ev||event; pos=getpos(eventr); disX=pos.x-this.offsetLeft; disY=pos.y-this.offsetTop; creatElement=document.createElement("div"); creatElement.className="boxs"; creatElement.style.width=odiv2.offsetWidth-2+"px"; creatElement.style.height=odiv2.offsetHeight-2+"px"; creatElement.style.top=odiv2.offsetTop+"px"; creatElement.style.left=odiv2.offsetLeft+"px"; div1.appendChild(creatElement); document.onmousemove=function(ev){ var eventr=ev||event; pos=getpos(eventr); creatElement.style.left=pos.x-disX+"px"; creatElement.style.top=pos.y-disY+"px"; if(creatElement.offsetTop<0){ creatElement.style.top=0+"px"; } if(creatElement.offsetLeft<0){ creatElement.style.left=0+"px"; } if(creatElement.offsetTop>odiv1.offsetHeight-odiv2.offsetHeight){ creatElement.style.top=odiv1.offsetHeight-odiv2.offsetHeight+"px"; } if(creatElement.offsetLeft>odiv1.offsetWidth-odiv2.offsetWidth){ creatElement.style.left=odiv1.offsetWidth-odiv2.offsetWidth+"px"; } } document.onmouseup=function(){ odiv2.style.left=creatElement.offsetLeft+"px"; odiv2.style.top=creatElement.offsetTop+"px"; div1.removeChild(creatElement); unEvent(odiv2,"mousedown"); document.onmousemove=null; } return false; }) } </script> </head> <body> <div id="div1"> <div id="div2"></div> </div> </body> </html>
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/8712.html