开始拖动一个DOM 属性为draggable 的元素后,是否可以停止拖动并退出拖放?

After starting the drag of a DOM element with draggable attribute , Could we stop dragging and exit from drag and drop?

我必须在拖动开始后停止异步拖动。我可以在拖动事件中添加一些东西来取消拖动吗?

document.querySelector('#drag-elem').addEventListener('drag', function(e){
  // Stop the drag
  e.preventDefault();
})

document.querySelector('#drag-elem').addEventListener('dragstart', function(e){
  console.log('dragstart')
})
<div draggable='true' id='drag-elem'>Draggable</div>

您可以使用 dataIsValid 标志来决定是否允许在 ondragoverondrop 事件处理程序中放置。举个例子,数据是0到1之间的随机数,大于0.5就认为有效,异步验证需要整整一秒。尝试将 Source 拖到 Target 上并等待至少一秒钟,然后再松开鼠标左键。

let dataIsValid = false;

function validateData(data) {
  dataIsValid = data.value > 0.5;
  console.log(`Data is ${dataIsValid ? "valid" : "invalid"}: ${data.value.toFixed(2)}`);
}

function onDragStart(event) {
  // Create data to be transferred
  const data = {
    value: Math.random()
  };
  event.dataTransfer.setData("text", JSON.stringify(data));
  event.target.textContent = data.value.toFixed(2);
  
  // Start asynchronous validation
  dataIsValid = false;
  setTimeout(() => validateData(data), 1000);
}

function onDragOver(event) {
  if (dataIsValid) {
    event.preventDefault();  
  }
}

function onDrop(event) {
  if (dataIsValid) {
    event.preventDefault();  
    const data = JSON.parse(event.dataTransfer.getData("text"));
    event.target.textContent = data.value.toFixed(2);
  }
}
div.circle {
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 100px;
  font-family: Arial, Helvetica, sans-serif;
}

div#source {
  background: coral;
}

div#target {
  background: lightblue;
}
<div id="source" class="circle" draggable="true" ondragstart="onDragStart(event)">Source</div>
<div id="target" class="circle" ondragover="onDragOver(event)" ondrop="onDrop(event)">Target</div>