参考这个答案:https://stackoverflow.com/a/6362527/3034646
我如何绑定触摸事件以便它们执行拖放事件? 我尝试将dragstart绑定到touchdown并将drop绑定到touchup,但这会导致dragstart无法在dataTransfer.get/setData上拾取。
是否可以映射触摸事件来复制拖放?
1.Touchstart 事件:该事件相当于dragstart。当用户触摸屏幕时触发。
// Get the element you want to make draggable
var draggableElement = document.getElementById('draggable');
// Add event listeners for touch events
draggableElement.addEventListener('touchstart', handleTouchStart, false);
draggableElement.addEventListener('touchmove', handleTouchMove, false);
draggableElement.addEventListener('touchend', handleTouchEnd, false);
// Variable to store initial touch position
var initialX = null;
var initialY = null;
// Function to handle touchstart event
function handleTouchStart(event) {
// Store initial touch position
initialX = event.touches[0].clientX;
initialY = event.touches[0].clientY;
}
// Function to handle touchmove event
function handleTouchMove(event) {
if (!initialX || !initialY) {
return;
}
// Calculate the distance moved
var deltaX = event.touches[0].clientX - initialX;
var deltaY = event.touches[0].clientY - initialY;
// Update the element's position
draggableElement.style.transform = 'translate(' + deltaX + 'px, ' + deltaY + 'px)';
// Prevent scrolling
event.preventDefault();
}
// Function to handle touchend event
function handleTouchEnd(event) {
// Reset initial touch position
initialX = null;
initialY = null;
// Perform actions equivalent to drop event
// For example, you can save the final position or perform any other necessary action
}
我建议使用这个https://github.com/bevacqua/dragula。非常容易集成。