js随机生成不同颜色块随机移动
2016-08-13 11:00
330 查看
<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 onclick="btn()">创建div</button> <script> function btn(){ var id; //动态创建元素 var str=document.createElement("div"); //元素的背景色随机的 str.style.backgroundColor=getColorRandom(); //将生成的div追加到body中 document.getElementById("body1").appendChild(str); //随机生成的id设置为动态创建的div的id str.id="items"+parseInt(Math.random()*10000); // 获取动态生成的div的id var obj=document.getElementById(str.id); var disX=0; var disY=0; //鼠标点击落下事件 obj.onmousedown=function (event){ disX=event.clientX-obj.offsetLeft; disY=event.clientY-obj.offsetTop; //鼠标移开事件 document.onmousemove=function(ev){ obj.style.left=ev.clientX-disX+"px"; obj.style.top=ev.clientY-disY+"px"; } //鼠标松开事件 document.onmouseup= function () { document.onmousemove=null; document.onmouseup=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>
相关文章推荐
- js生成随机数字.用到那个静态页面随机变换背景图片!
- js 生成随机汉字的问题
- 随机生成不同的图形
- 试验十:随机生成10个不同的数
- 随机生成n个不同的数字小组合作编写
- 用js来生成随机彩票号码清单
- 随机生成十个不同的数
- 用JS写了一个随机取不同的数据的例子
- 自我补充篇之java随机验证码的生成(字母不同色,干扰线无规律颜色也不同)
- 随机生成十个不同的数
- js 生成随机汉字的问题
- JS代码实例:实现随机加载不同的CSS样式
- 生成大量随机字符串不同实现方式的效率对比
- VB----随机生成一个不同种类的图形
- js生成随机字母
- 利用随机类生成数组,并用冒泡排序以及选择排序对不同数组的元素进行从小到大的排序
- 生成大量随机字符串不同实现方式的效率对比
- JS生成随机颜色
- 随机生成十个不同的数
- 随机生成十个不同的数