js实现方块拖曳
实现方块拖曳的基本步骤
通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖曳功能。以下是核心代码示例:
const box = document.getElementById('draggable-box');
let isDragging = false;
let offsetX, offsetY;
box.addEventListener('mousedown', (e) => {
isDragging = true;
offsetX = e.clientX - box.getBoundingClientRect().left;
offsetY = e.clientY - box.getBoundingClientRect().top;
box.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
box.style.left = `${e.clientX - offsetX}px`;
box.style.top = `${e.clientY - offsetY}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
box.style.cursor = 'grab';
});
CSS 基础样式
确保方块使用绝对定位以便移动:

#draggable-box {
position: absolute;
width: 100px;
height: 100px;
background-color: #3498db;
cursor: grab;
user-select: none; /* 防止拖动时选中文本 */
}
边界限制
防止方块被拖出视口:

document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const x = e.clientX - offsetX;
const y = e.clientY - offsetY;
const maxX = window.innerWidth - box.offsetWidth;
const maxY = window.innerHeight - box.offsetHeight;
box.style.left = `${Math.min(Math.max(0, x), maxX)}px`;
box.style.top = `${Math.min(Math.max(0, y), maxY)}px`;
});
触摸屏支持
添加触摸事件以实现移动端兼容:
box.addEventListener('touchstart', (e) => {
isDragging = true;
const touch = e.touches[0];
offsetX = touch.clientX - box.getBoundingClientRect().left;
offsetY = touch.clientY - box.getBoundingClientRect().top;
});
document.addEventListener('touchmove', (e) => {
if (!isDragging) return;
const touch = e.touches[0];
box.style.left = `${touch.clientX - offsetX}px`;
box.style.top = `${touch.clientY - offsetY}px`;
});
document.addEventListener('touchend', () => {
isDragging = false;
});
性能优化
使用 transform 替代 left/top 提升动画性能:
box.style.transform = `translate(${x}px, ${y}px)`;
完整示例
查看 CodePen 完整示例(需替换为实际链接)






