简体   繁体   English

什么是DragEvent的移动等价方式?

[英]What's the mobile equivalent of DragEvent?

I made a carousel and my dragevent works fine on computer but doesn't on mobile. 我做了一个轮播,我的dragevent在计算机上可以正常运行,但不能在移动设备上运行。

I've seen someone suggest to use touchEvent but touchEvent doesn't work on either. 我见过有人建议使用touchEvent,但touchEvent都不适用。

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 如果我使用touchstart或touchend执行相同的请求,则该事件没有任何价值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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