<!doctype html> <html> <head> <meta charset="utf-8"> <title>原生js元素创建及拖拽</title> <style> body,ul,li { margin:0;} ul { padding:0; list-style:none;} ul { width:40px; float:left; padding-left:50px;} li { width:10px; height:10px; margin:10px 5px 0 5px; background-color:red; float:left; cursor:pointer; background:#FFF} #height{ height:720px;} #minbox{ width:1000px; height:500px; border:10px solid red; float:left; position:relative;} .ceretdiv { position:absolute; left:0; top:0;} </style> <script> window.onload=function(){ var aLi = document.getElementById("colorbox").getElementsByTagName("li"); var minBox = document.getElementById("minbox"); var inum=1; for(var i = 0;i<aLi.length;i++) { aLi[i].style.backgroundColor=aLi[i].getAttribute("data-value"); aLi[i].onclick=function(){ var tianjia=document.createElement("div"); tianjia.id="div"+inum; inum++; tianjia.className="ceretdiv" tianjia.style.width="50"+'px'; tianjia.style.height="50"+'px'; tianjia.style.backgroundColor=this.getAttribute("data-value"); minBox.appendChild(tianjia); move(tianjia.id); } } } var zIndex=1; function move(id){ var oMove=document.getElementById(id); var minBox = document.getElementById("minbox"); oMove.onmousedown=function(ev){ this.style.zIndex=zIndex; zIndex++; var ev=window.event || ev; var offX=oMove.offsetLeft; var offY=oMove.offsetTop; var StartX=ev.clientX; var StartY=ev.clientY; document.onmousemove=function(ev){ var ev=window.event || ev; var l=0; var t=0; l=ev.clientX-StartX+offX; t=ev.clientY-StartY+offY; if(l<0){ l=0; } if(l>(minBox.offsetWidth-oMove.offsetWidth-20)){ l=minBox.offsetWidth-oMove.offsetWidth-20+"px" } if(t<0){ t=0; } if(t>(minBox.offsetHeight-oMove.offsetHeight-20)){ t= minBox.offsetHeight-oMove.offsetHeight-20+"px" } oMove.style.left=l+'px'; oMove.style.top=t+'px'; return false; } document.onmouseup=function(){ document.onmouseup=null; document.onmousemove=null; } return false; }; } </script> </head> <body> <div id="height"> <div id="minbox"></div> <ul id="colorbox"> <li data-value="#030"></li> <li data-value="#033"></li> <li data-value="#036"></li> <li data-value="#039"></li> <li data-value="#03c"></li> <li data-value="#03F"></li> <li data-value="#930"></li> <li data-value="#933"></li> <li data-value="#936"></li> <li data-value="#939"></li> </ul> </div> </body> </html>