<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#box>div{
100px;
height: 100px;
background: red;
border-radius: 10px;
font-size: 30px;
position: absolute;
line-height: 100px;
text-align: center;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var oBox=document.getElementById('box');
var ml=mt=20;
for(var i=0;i<3;i++){
for(var j=0;j<3;j++){
var odiv=document.createElement('div');
oBox.appendChild(odiv);
odiv.style.left=j*(odiv.offsetWidth+ml)+"px";
odiv.style.top=i*(odiv.offsetHeight+mt)+"px";
odiv.style.background="rgba("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")";
}
}
var arrF="ABCDEFGHI";
var odiv=oBox.children;
for(var i=0;i<arrF.length;i++){
odiv[i].innerText=arrF.charAt(i);
}
for(var i=0;i<odiv.length;i++){
odiv[i].onmousedown=function(e){
var evt = e || event;
var x1=evt.offsetX;
var y1=evt.offsetY;
var drag=this;
var ndiv=this.cloneNode();
oBox.replaceChild(ndiv,drag);
oBox.appendChild(drag);
this.style.zIndex="1";
document.onmousemove=function(e){
var evt = e || event;
var x=evt.clientX;
var y=evt.clientY;
drag.style.left=x-x1+"px";
drag.style.top=y-y1+"px";
}
document.onmouseup=function(){
document.onmousemove=null;
var arr=[];
var narr=[];
for(var j=0;j<odiv.length-1;j++){
var x=drag.offsetLeft-odiv[j].offsetLeft;
var y=drag.offsetTop-odiv[j].offsetTop;
var dleng=Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
arr.push(dleng);
narr.push(dleng);
}
arr.sort(function(a,b){
return a-b;
})
var mindex=narr.indexOf(arr[0]);
drag.style.left=odiv[mindex].style.left;
drag.style.top=odiv[mindex].style.top;
odiv[mindex].style.left=ndiv.style.left;
odiv[mindex].style.top=ndiv.style.top;
oBox.removeChild(ndiv);
document.onmouseup=null;
}
return false;
}
}
</script>
</body>
</html>