代码收藏(五)JavaScript 随机创建DIV 并拖动DIV

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var div, wah, index, arr = [];
        document.addEventListener("click", clickHandler);
        function clickHandler(e) {
            if (e.target === document.documentElement)
                createDiv(e);
            for (var i = 0; i < arr.length; i++) {
                arr[i].addEventListener("mousedown",mousedownHandler);
            }
        }
        
        //移动DIV
        function mousedownHandler(e) {
            if (e.type === "mousedown") {
                document.div = e.target;
                document.offset={x:e.offsetX,y:e.offsetY};
                document.addEventListener("mousemove", mousedownHandler);
                document.addEventListener("mouseup", mousedownHandler);
            } else if (e.type === "mousemove") {
                document.div.style.top = e.clientY-document.offset.y + "px";
                document.div.style.left = e.clientX-document.offset.x + "px";
            } else if (e.type === "mouseup") {
                document.removeEventListener("mousemove", mousedownHandler);
                document.removeEventListener("mouseup", mousedownHandler);
            }
        }

        //创建DIV
        function createDiv(e) {
            wah = obj.ceSize(100, 20);
            div = obj.ce("div", {
                width: wah + "px",
                height: wah + "px",
                backgroundColor: obj.ceColor(),
                position: "absolute",
                top: e.clientY - wah / 2 + "px",
                left: e.clientX - wah / 2 + "px"
            })
            arr.push(div);
            document.body.appendChild(div);
        }
        var obj = {
            ce: function (type, style) {
                var elem = document.createElement(type);
                Object.assign(elem.style, style);
                return elem;
            },
            ceSize: function (MAX, MIN) {
                size = Math.floor(Math.random() * (MAX - (MIN ? MIN : 0)) + (MIN ? MIN : 0));
                return size;
            },
            ceColor: function () {
                color = "#" + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0");
                return color;
            },
        }
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值