<!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>
代码收藏(五)JavaScript 随机创建DIV 并拖动DIV
最新推荐文章于 2022-07-12 16:15:24 发布