<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
margin-left: 10px;
float: left;
}
</style>
</head>
<body id="body1">
<button οnclick="btn()">创建div</button>
<script>
function btn(){
var id;
var str=document.createElement("div");
str.style.backgroundColor=getColorRandom();
document.getElementById("body1").appendChild(str);
str.id="items"+parseInt(Math.random()*10000);
var obj=document.getElementById(str.id);
var disX=0;
var disY=0;
obj.οnmοusedοwn=function (event){
disX=event.clientX-obj.offsetLeft;
disY=event.clientY-obj.offsetTop;
document.οnmοusemοve=function(ev){
obj.style.left=ev.clientX-disX+"px";
obj.style.top=ev.clientY-disY+"px";
}
document.οnmοuseup= function () {
document.οnmοusemοve=null;
document.οnmοuseup=null;
}
}
function getColorRandom(){
var c="#";
var cArray=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
for(var i=0;i<6;i++){
var cIndex= Math.round(Math.random()*15);
c+=cArray[cIndex];
}
return c;
}
}
</script>
</body>