拖放Javascript无法在移动设备上运行

时间:2017-01-30 12:28:51

标签: javascript mobile draggable

Tutorial for HTML5 drag&drop - sortable list

但脚本不适用于移动设备。我被尝试了sortable.js和插件。一切都不适合项目。这对我有帮助。但移动设备正在运行

<ul>
  <li draggable="true" ondragenter="dragenter(event)" ondragstart="dragstart(event)">Apples</li>
  <li draggable="true" ondragenter="dragenter(event)" ondragstart="dragstart(event)">Oranges</li>
  <li draggable="true" ondragenter="dragenter(event)" ondragstart="dragstart(event)">Bananas</li>
  <li draggable="true" ondragenter="dragenter(event)" ondragstart="dragstart(event)">Strawberries</li>
</ul>
<script type="text/javascript">
  var source;

  function isbefore(a, b) {
    if (a.parentNode == b.parentNode) {
      for (var cur = a; cur; cur = cur.previousSibling) {
        if (cur === b) { 
          return true;
        }
      }
    }
    return false;
  } 

  function dragenter(e) {
    if (isbefore(source, e.target)) {
      e.target.parentNode.insertBefore(source, e.target);
    }
    else {
      e.target.parentNode.insertBefore(source, e.target.nextSibling);
    }
  }

  function dragstart(e) {
    source = e.target;
    e.dataTransfer.effectAllowed = 'move';
  }

</script>

1 个答案:

答案 0 :(得分:0)

您的问题的答案(不使用jQuery或其他库)是因为某些移动设备不听取拖动事件。

看看这个问题,我相信和你有同样的问题。

html5 drag and drop FOR MOBILE

  

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

 <!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>