原生拖放目标不可丢弃(但其子项是)

时间:2018-02-05 17:56:49

标签: javascript html5 drag-and-drop

我正在尝试使用HTML5本机拖放实现行重新排序:只需拖动即可重新排序行。源也是目标,当被删除时,源移动到目标前面。

此示例部分有效,但问题是只有在放入预期放置目标的子输入类型元素之一时,放置才会成功。为什么drop只对这些子元素成功,而不是它们的父行div?

function handle_dragleave(ev) {
  ev.preventDefault();
  ev.stopPropagation();
  ev.currentTarget.setAttribute('style', "border-top:none;");
}

function handle_dragstart(ev) {
  console.log("drag: " + ev.currentTarget.id);
  ev.stopPropagation();
  ev.currentTarget.style.border = "dashed";
  ev.dataTransfer.setData("text/plain", ev.currentTarget.id);
}

function handle_drop(ev) {
  console.log("drop: " + ev.currentTarget.id);
  ev.preventDefault();
  ev.stopPropagation();
  var sourceId = ev.dataTransfer.getData("text");
  var source = document.getElementById(sourceId);
  ev.currentTarget.before(source);
  ev.currentTarget.style.border = "none";
  ev.dataTransfer.clearData();
}

function handle_dragover(ev) {
  ev.stopPropagation();
  ev.currentTarget.setAttribute('style', "border-top:solid;");
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">
  <div id="r1" class="row" style="cursor:move" draggable="true" 
    ondragleave="handle_dragleave(event)" ondragstart="handle_dragstart(event)" 
    ondrop="handle_drop(event, this)" ondragover="handle_dragover(event)">
    <div>
      <div class="col-xs-1"></div>
      <div class="col-xs-6">
        <textarea class="form-control">First</textarea>
      </div>
      <div class="col-xs-4">
        <input class="form-control"/>
      </div>
      <div class="col-xs-1">
        <button type="submit" class="btn btn-default"/>
      </div>
    </div>
    <div>
      <div class="col-xs-12"><hr/></div>
    </div>
  </div>
  <div id="r2" class="row" style="cursor:move" draggable="true" 
    ondragleave="handle_dragleave(event)" ondragstart="handle_dragstart(event)" 
    ondrop="handle_drop(event, this)" ondragover="handle_dragover(event)">
    <div>
      <div class="col-xs-1"></div>
      <div class="col-xs-6">
        <textarea class="form-control">Second</textarea>
      </div>
      <div class="col-xs-4">
        <input class="form-control"/>
      </div>
      <div class="col-xs-1">
        <button type="submit" class="btn btn-default"/>
      </div>
    </div>
    <div>
      <div class="col-xs-12"><hr/></div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

要使元素可以删除,必须阻止dragover事件中的默认操作:

function handle_dragover(ev)
{ 
  ev.preventDefault(); // Necessary. Allows us to drop.    
  ev.currentTarget.setAttribute('style', "border-top:solid;");   
}

stopPropagation();似乎也没有必要使其正常工作。