使用mousedown, mousemove, mouseup事件
mousedown事件触发后,开始拖拽
mousemove时,需要通过event.clientX和clientY获取拖拽位置,并实时更新位置
mouseup时,拖拽结束
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable Element</title>
<style>
.draggable {
position: absolute;
width: 200px;
height: 200px;
background-color: #f00;
cursor: move;
}
</style>
</head>
<body>
<div id="draggable" class="draggable"></div>
<script>
// 获取需要拖拽的节点
var draggableNode = document.getElementById('draggable');
// 初始化拖拽状态
var isDragging = false;
var offset = { x: 0, y: 0 };
// 绑定 mousedown 事件
draggableNode.addEventListener("mousedown", function(event) {
// 设置拖拽状态为 true
isDragging = true;
// 计算鼠标相对于节点的偏移量
offset.x = event.clientX - draggableNode.offsetLeft;
offset.y = event.clientY - draggableNode.offsetTop;
});
// 绑定 mousemove 事件
draggableNode.addEventListener("mousemove", function(event) {
// 如果处于拖拽状态
if (isDragging) {
// 计算节点的新位置
var left = event.clientX - offset.x;
var top = event.clientY - offset.y;
// 更新节点的位置
draggableNode.style.left = left + "px";
draggableNode.style.top = top + "px";
}
});
// 绑定 mouseup 事件
draggableNode.addEventListener("mouseup", function() {
// 设置拖拽状态为 false
isDragging = false;
});
</script>
</body>
</html>
通过上述代码可以实现一个简单的拖拽功能,复制可用。