html5拖放FOR MOBILE

Sno*_*uin 12 javascript mobile jquery html5 drag-and-drop

我在w3schools上发现这个代码用于拖放,它可以在桌面上运行,但不适用于移动设备.

我需要修改什么才能识别触摸?

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script>
function allowDrop(ev)
{
ev.preventDefault();
}

function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Ale*_*ore 12

大多数移动设备不会侦听绑定到DOM的拖动事件.我建议使用touchmove事件以及随之而来的事件.它看起来像:

选项1

 <!DOCTYPE HTML>
 <html>
 <head>
 <style type="text/css">
       #div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
 </style>
 </head>
 <body>

 <p>Drag the W3Schools image into the rectangle:</p>

 <div id="div1"></div>
 <br>
 <img id="drag1" src="img_logo.gif width="336" height="69">

 <script type="text/javascript">
  var el = document.getElementById('drag'); 

  el.addEventListener("touchstart", handleStart, false);
  el.addEventListener("touchend", handleEnd, false);
  el.addEventListener("touchcancel", handleCancel, false);
  el.addEventListener("touchleave", handleEnd, false);
  el.addEventListener("touchmove", handleMove, false);

  function handleStart(event) {
      // Handle the start of the touch
  }

  // ^ Do the same for the rest of the events

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

handleStart,handleEnd等是从事件触发的回调,这是您可以处理触摸事件的地方.

如果你不想对触摸事件做所有繁重的工作,那么我会推荐一个像JQuery Touch Punch这样的库.我已经使用过了,它在iOS上运行得很好.

这是图书馆的链接,您还可以在自己的移动设备中测试其性能:http://touchpunch.furf.com/

选项2(更好的选项) JQuery Touch打孔包含如下:

在您的页面上包含jQuery和jQuery UI.

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script>

// Download this from the link above
<script src="jquery.ui.touch-punch.min.js"></script>

<script>
    $('#drag1').draggable();
    $( "#div1" ).droppable({
        drop: function( event, ui ) {
          $( this )
            .addClass( "isDropped" )
            .html( "Dropped!" );
        }
      });
    });

</script>
Run Code Online (Sandbox Code Playgroud)

  • @crock这个答案是3年前选出的,可能已经过时了.此外,如果您正在寻求帮助,"不工作"不是非常有用的回应.描述您尝试过的内容,预期结果并将其与您观察到的实际结果进行比较. (4认同)
  • 我已经在 Android 设备中使用 Firefox 和 Chrome 测试了您的链接,但它不起作用 (2认同)