javascript - html5 拖放移动设备

标签 javascript jquery html mobile 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>

最佳答案

大多数移动设备不监听绑定(bind)到 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>

handleStart、handleEnd 等是您从事件中触发的回调,您可以在其中处理触摸事件。

如果您不想完成触摸事件方面的所有繁重工作,那么我会推荐一个库,例如 JQuery Touch Punch。我用过它,它在 iOS 上运行良好。

这是库的链接,您还可以在您自己的移动设备上测试它的性能:http://touchpunch.furf.com/

选项 2(更好的选项) JQuery Touch punch 是这样包含的:

在您的页面上包含 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>

关于javascript - html5 拖放移动设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927759/

相关文章:

javascript - 遍历JSON对象创建jsTree

javascript - 为 Iframe 的父 div 标签设置宽度

javascript - 如何使用 data- 属性设置选择 HTML 标签的选项

JavaScript 对象访问;输出正常,选择不起作用

java - 具有多个 Action 的形式?

javascript - 使用 REST API 的 Dynamics CRM 2011 搜索

javascript - Angular 2 中输入的更改事件不起作用

php textarea使用jquery/ajax自动保存到sql

javascript - 从 localStorage 保存和加载图像

html - 图片总是在页面底部,无论多长时间