[javascript] 자바스크립트에서 터치 이벤트를 사용하여 터치한 엘리먼트를 드래그 앤 드롭하는 방법은?
-
터치 이벤트 등록:
touchstart
,touchmove
,touchend
이벤트를 사용하여 터치 이벤트를 감지합니다.const element = document.getElementById('targetElement'); let posX, posY, initialX, initialY = 0; element.addEventListener('touchstart', function(e) { initialX = e.touches[0].clientX - posX; initialY = e.touches[0].clientY - posY; }); element.addEventListener('touchmove', function(e) { posX = e.touches[0].clientX - initialX; posY = e.touches[0].clientY - initialY; // 여기서 새로운 위치로 element를 이동시키는 코드를 작성합니다. }); element.addEventListener('touchend', function() { // 드래그가 끝났을 때 실행되는 코드를 작성합니다. });
-
드래그 앤 드롭 로직 구현:
touchstart
이벤트로 초기 터치 위치를 기억하고,touchmove
이벤트로 엘리먼트의 위치를 업데이트합니다.element.addEventListener('touchstart', function(e) { posX = e.touches[0].clientX; posY = e.touches[0].clientY; }); element.addEventListener('touchmove', function(e) { posX = e.touches[0].clientX - initialX; posY = e.touches[0].clientY - initialY; element.style.transform = `translate(${posX}px, ${posY}px)`; });
이러한 방법을 사용하여 자바스크립트에서 터치 이벤트를 통해 엘리먼트를 드래그 앤 드롭할 수 있습니다.