// HTML 结构示例
<div id="draggable" style="width: 100px; height: 100px; background-color: red; position: absolute; cursor: move;">拖拽我</div>
<script>
// JavaScript 拖拽实现
let active = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
const draggableElement = document.getElementById('draggable');
draggableElement.addEventListener('mousedown', dragStart, false);
document.addEventListener('mouseup', dragEnd, false);
document.addEventListener('mousemove', drag, false);
function dragStart(e) {
if (e.target === draggableElement) {
active = true;
currentX = e.clientX - xOffset;
currentY = e.clientY - yOffset;
initialX = draggableElement.offsetLeft;
initialY = draggableElement.offsetTop;
}
}
function dragEnd() {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
xOffset = e.clientX - currentX;
yOffset = e.clientY - currentY;
draggableElement.style.left = (initialX + xOffset) + 'px';
draggableElement.style.top = (initialY + yOffset) + 'px';
}
}
</script>
这是一个简单的HTML和JavaScript示例,展示了如何创建一个可拖拽的`div`元素。通过监听`mousedown`、`mouseup`和`mousemove`事件,并相应地更新`div`的`left`和`top`样式属性,实现拖拽功能。请确保你的HTML文件中包含了这个`div`元素和相应的JavaScript代码。