简体   繁体   中英

What's the mobile equivalent of DragEvent?

I made a carousel and my dragevent works fine on computer but doesn't on mobile.

I've seen someone suggest to use touchEvent but touchEvent doesn't work on either.

const $img = document.querySelector('img');

$img.addEventListener('dragstart', function(e){ console.log(`Start: ${e.screenX}`) },false);

$img.addEventListener('dragend', function(e){ console.log(`End: ${e.screenX}`) },false)

if i do the same request using touchstart or touchend i get no value on the event

/* event does not fire */
$img.addEventListener('touchstart', function(e){ console.log(`Evento: ${e.screenX}`) }, false)

On mobile, you can use:

 <html> <body> <p id="test">Drag Me!</p> <script> const p = document.getElementById("test"); p.addEventListener("dragstart", handleStuff, false); p.addEventListener("touchstart", touch2drag, false); function handleStuff(e) { e.stopPropagation(); e.preventDefault(); if (e.clientX) { console.log(`Stuff happened at ${e.clientX}x;${e.clientY}.`); } } function touch2drag(e) { e.stopPropagation(); e.preventDefault(); // translate to mouse event let clkEvt = document.createEvent("MouseEvent"); clkEvt.initMouseEvent(e.type.replace("touch", "drag"), true, true, window, e.detail, e.touches[0].screenX, e.touches[0].screenY, e.touches[0].clientX, e.touches[0].clientY, false, false, false, false, 0, null); p.dispatchEvent(clkEvt); // or just handle touch event handleStuff(e); } </script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM