< html xmlns ="http://www.w3.org/1999/xhtml" > < head runat ="server" > < title > 移动Div层 </ title > </ head > < body onmousemove ="window.status = 'X='+event.x+'Y='+event.y" > < form id ="form1" runat ="server" > < div > < div id ="panl" style ='position: absolute; left: 0px; top:0px ; background-color:Blue; width:900px ; height:600px ;' > </ div > < input id ="Button1" style ="position:absolute; left: 0px; top:300px ; width:50px ; height:40px; " type ="button" value ="添加" onclick ="addDiv()" /> < input id ="Button2" style ="position:absolute; left:50px; top:300px; width:50px; height:40px;" type ="button" value ="显示" onclick ="saveDiv()" > </ div > < script language ="javascript" type ="text/javascript" > // Arnold Elric Date:07-10-10 var myArray=new Array; //全局变量var Obj='';var px=0;var py=0;var i=1;function addDiv() //添加Div{var Name="Name"+i;var x=Math.floor(Math.random()*(900-70));var y=Math.floor(Math.random()*(600-70));var arr=new Array();arr[0]=Name;arr[1]=x;arr[2]=y;myArray[myArray.length]=arr;var str='';str+="<div id="+Name+" style='position: absolute; left:"+x+"px; top:"+y+"px; background-color:Red; width:70px; height:70px; ' οnmοusedοwn=MD(this) οnmοusemοve=MM() οnmοuseup=MU() ><input id='img"+Name+" ' style=' width:30px; height:25px; 'type='button' value='关闭' οnclick=closeDiv("+Name+") ></div></div>";var Div=document.getElementById("panl");Div.insertAdjacentHTML('beforeEnd',str);i++;}function saveDiv() //显示Div { var str=''; for(var i=0;i<myArray.length;i++) { str+="id: "+myArray[i][0]+" left:"+myArray[i][1]+"px"+" top:"+myArray[i][2]+"px"+"/n"; } alert(str);}function closeDiv(DivID) //关闭Div{ deleteDate(DivID); var div=document.getElementById("panl"); div.removeChild(DivID);}function MD(object) //鼠标放下{ Obj=object.id; document.all(Obj).setCapture(); px=event.x-document.all(Obj).style.pixelLeft; // 计算鼠标偏移 py=event.y-document.all(Obj).style.pixelTop; }function MM() //鼠标移动{ if(Obj!='') { document.all(Obj).style.left=event.x-px; document.all(Obj).style.top=event.y-py; }}function MU() //鼠标抬起{ if(Obj!='') { document.all(Obj).releaseCapture(); changeDate(); Obj=''; }}function changeDate() //移动Div后 改变数组中的值{ for(var i=0;i<myArray.length;i++) { if(Obj==myArray[i][0]) { myArray[i][1]=event.x-px; myArray[i][2]=event.y-py; } }}function deleteDate(DivID)//删除存在数组中的那条Div 纪录{ for(var i=0;i<myArray.length;i++) { if(DivID.id==myArray[i][0]) { myArray.splice(i,1); } }} </ script > </ form > </ body > </ html >