HTML5利用鼠标拖拽元素写一个div方块,鼠标可以任意拖拽一个div方块
时间: 2024-03-17 10:39:49 浏览: 92
可以使用HTML5中的Drag API来实现鼠标拖拽元素。以下是一个简单的示例:
```
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<style>
#myDiv {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
cursor: move;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<script>
var dragItem = document.getElementById("myDiv");
var posX = 0, posY = 0;
var mouseX = 0, mouseY = 0;
function dragMouseDown(event) {
event.preventDefault();
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) {
document.removeEventListener("mousemove", dragMouseMove);
document.removeEventListener("mouseup", dragMouseUp);
}
dragItem.addEventListener("mousedown", dragMouseDown);
</script>
</body>
</html>
```
在以上示例中,我们创建了一个id为"myDiv"的div方块,并使用CSS设置其样式。然后,在JavaScript中,我们获取该元素并添加mousedown事件监听器。当用户按下鼠标按钮时,dragMouseDown函数将被调用。在该函数中,我们记录鼠标的初始位置,并添加mousemove和mouseup事件监听器。在mousemove事件处理程序中,我们计算鼠标移动的距离,并根据该距离更新元素的位置。在mouseup事件处理程序中,我们移除事件监听器。
阅读全文