簡體   English   中英

什么是DragEvent的移動等價方式?

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

我做了一個輪播,我的dragevent在計算機上可以正常運行,但不能在移動設備上運行。

我見過有人建議使用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)

如果我使用touchstart或touchend執行相同的請求,則該事件沒有任何價值

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

在移動設備上,您可以使用:

 <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