JavaScript 拖放(Drag and Drop,简称DnD)是一种允许用户通过鼠标操作来移动网页元素的技术。碰撞检测则是判断两个或多个元素是否发生了接触或重叠的过程。
以下是一个简单的JavaScript拖放示例,包含基本的碰撞检测:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop with Collision Detection</title>
<style>
.draggable {
width: 100px;
height: 100px;
background-color: blue;
color: white;
text-align: center;
line-height: 100px;
position: absolute;
cursor: grab;
}
.droppable {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 300px;
left: 100px;
}
</style>
</head>
<body>
<div class="draggable" id="draggable">Drag me</div>
<div class="droppable" id="droppable"></div>
<script>
const draggable = document.getElementById('draggable');
const droppable = document.getElementById('droppable');
let offsetX, offsetY;
draggable.addEventListener('mousedown', (e) => {
offsetX = e.clientX - draggable.offsetLeft;
offsetY = e.clientY - draggable.offsetTop;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
function onMouseMove(e) {
draggable.style.left = (e.clientX - offsetX) + 'px';
draggable.style.top = (e.clientY - offsetY) + 'px';
checkCollision();
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
function checkCollision() {
const draggableRect = draggable.getBoundingClientRect();
const droppableRect = droppable.getBoundingClientRect();
if (
draggableRect.left < droppableRect.right &&
draggableRect.right > droppableRect.left &&
draggableRect.top < droppableRect.bottom &&
draggableRect.bottom > droppableRect.top
) {
droppable.style.backgroundColor = 'green';
} else {
droppable.style.backgroundColor = 'red';
}
}
</script>
</body>
</html>
问题:拖放元素时出现卡顿或不流畅的现象。
原因:可能是由于频繁的重绘和回流导致的性能问题。
解决方法:
transform
属性代替 top
和 left
来移动元素,因为 transform
不会触发回流。mousemove
事件中使用 requestAnimationFrame
来优化性能。function onMouseMove(e) {
requestAnimationFrame(() => {
draggable.style.transform = `translate(${e.clientX - offsetX}px, ${e.clientY - offsetY}px)`;
checkCollision();
});
}
通过这些优化,可以显著提高拖放操作的流畅性。
领取专属 10元无门槛券
手把手带您无忧上云