在JavaScript中,移动端拖放(Drag and Drop, DnD)是指用户可以通过触摸屏幕来拖动一个元素,并将其放置到另一个位置。这个功能通常用于列表项的重新排序、元素的布局调整等场景。
touchstart
, touchmove
, touchend
)来实现。以下是一个简单的基于事件的拖放示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mobile Drag and Drop</title>
<style>
.draggable {
width: 100px;
height: 100px;
background-color: #f00;
margin: 10px;
touch-action: none; /* 禁用浏览器默认的触摸行为 */
}
</style>
</head>
<body>
<div class="draggable" id="item1"></div>
<div class="draggable" id="item2"></div>
<script>
const items = document.querySelectorAll('.draggable');
let activeItem = null;
let initialX, initialY;
items.forEach(item => {
item.addEventListener('touchstart', handleTouchStart);
item.addEventListener('touchmove', handleTouchMove);
item.addEventListener('touchend', handleTouchEnd);
});
function handleTouchStart(e) {
activeItem = e.target;
initialX = e.touches[0].clientX - activeItem.offsetLeft;
initialY = e.touches[0].clientY - activeItem.offsetTop;
}
function handleTouchMove(e) {
if (activeItem) {
e.preventDefault(); // 阻止默认滚动行为
activeItem.style.left = `${e.touches[0].clientX - initialX}px`;
activeItem.style.top = `${e.touches[0].clientY - initialY}px`;
activeItem.style.position = 'absolute';
}
}
function handleTouchEnd() {
activeItem = null;
}
</script>
</body>
</html>
touchmove
事件中没有正确计算位置。确保每次移动都基于最新的触摸点坐标。handleTouchMove
中始终使用e.touches[0]
获取当前触摸点的坐标。handleTouchMove
中使用e.preventDefault()
来阻止默认的滚动行为。requestAnimationFrame
来优化重绘和回流,或者使用CSS3的transform
属性来代替left
和top
,因为后者会触发重排。通过以上方法,可以有效实现移动端的拖放功能,并解决常见的实现问题。
没有搜到相关的文章