HTML5利用鼠标拖拽元素创建多个div方块,鼠标可以任意拖拽一个div方块
时间: 2024-03-17 14:39:54 浏览: 102
要创建多个div方块,我们可以使用JavaScript动态创建元素,并将它们添加到HTML文档中。以下是一个例子:
```
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop Multiple Elements</title>
<style>
.myDiv {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<script>
var container = document.body;
var divCount = 5;
var divs = [];
for (var i = 0; i < divCount; i++) {
var div = document.createElement("div");
div.className = "myDiv";
div.style.left = Math.floor(Math.random() * container.offsetWidth) + "px";
div.style.top = Math.floor(Math.random() * container.offsetHeight) + "px";
container.appendChild(div);
divs.push(div);
}
var dragItem = null;
var posX = 0, posY = 0;
var mouseX = 0, mouseY = 0;
function dragMouseDown(event) {
event.preventDefault();
dragItem = this;
posX = event.clientX;
posY = event.clientY;
document.addEventListener("mousemove", dragMouseMove);
document.addEventListener("mouseup", dragMouseUp);
}
function dragMouseMove(event) {
event.preventDefault();
mouseX = posX - event.clientX;
mouseY = posY - event.clientY;
posX = event.clientX;
posY = event.clientY;
dragItem.style.left = (dragItem.offsetLeft - mouseX) + "px";
dragItem.style.top = (dragItem.offsetTop - mouseY) + "px";
}
function dragMouseUp(event) {
dragItem = null;
document.removeEventListener("mousemove", dragMouseMove);
document.removeEventListener("mouseup", dragMouseUp);
}
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("mousedown", dragMouseDown);
}
</script>
</body>
</html>
```
在以上示例中,我们使用一个for循环来创建5个div方块。在创建每个div时,我们设置其样式和随机的位置,并将其添加到文档中。我们还将每个div元素添加到一个数组中,以便稍后使用。
然后,我们创建了三个事件处理程序:dragMouseDown、dragMouseMove和dragMouseUp。当用户按下鼠标按钮时,dragMouseDown函数将被调用,并设置dragItem变量为当前被拖拽的div元素。在mousemove事件处理程序中,我们计算鼠标移动的距离,并根据该距离更新元素的位置。在mouseup事件处理程序中,我们将dragItem变量重置为null,并移除事件监听器。
最后,我们使用一个for循环,将mousedown事件监听器添加到每个div元素上,以便它们可以被拖拽。
阅读全文