1. 程式人生 > >js隨機生成不同顏色塊隨機移動

js隨機生成不同顏色塊隨機移動

<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>