将拖放事件绑定到触摸事件

问题描述 投票:0回答:2

参考这个答案:https://stackoverflow.com/a/6362527/3034646

我如何绑定触摸事件以便它们执行拖放事件? 我尝试将dragstart绑定到touchdown并将drop绑定到touchup,但这会导致dragstart无法在dataTransfer.get/setData上拾取。

是否可以映射触摸事件来复制拖放?

html drag-and-drop touch
2个回答
0
投票

1.Touchstart 事件:该事件相当于dragstart。当用户触摸屏幕时触发。

  1. Touchmove 事件:该事件将模拟拖动行为。当用户在触摸屏幕时移动手指时会触发。
  2. Touchend 事件:该事件相当于 drop 事件。当用户拖动后将手指离开屏幕时会触发。

// 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
}


-1
投票

我建议使用这个https://github.com/bevacqua/dragula。非常容易集成。

© www.soinside.com 2019 - 2024. All rights reserved.