HTML5拖放 - 火狐浏览器正在重定向

21

我正在尝试在我的应用程序中实现HTML5的拖放功能,但是Firefox始终会重定向到放置的图片源。我使用了e.stopPropagation()。在Chromium中,一切都按预期工作。

<section class="desktop">
  <img class="icon" style="left: 0px; top: 340px;" src="./computer.png" />
  <img class="icon" style="left: 0px; top: 170px;" src="./documents.png" />
  <img class="icon" style="left: 0px; top: 0px;" src="./bin.png" />
</section>
<script>
  window.clickedIcons = [];
  window.draggedIcon = {
    offset: [0, 0],
    element: null
  };

  //Drag & drop
  function dragStart(e) {
    window.draggedIcon.element = e.target;
    event.dataTransfer.effectAllowed = 'copyMove';
    event.dataTransfer.setData('text/plain', 'hey'); //hack

    const style = getComputedStyle(event.target);
    draggedIcon.element = event.target;
    draggedIcon.offset[0] =
        parseInt(style.getPropertyValue("left")) - event.clientX;
    draggedIcon.offset[1] =
        parseInt(style.getPropertyValue("top" )) - event.clientY;
  }

  function dragOver(e) {
    e.preventDefault();
    return false;
  }
       
  function drop(e) {
    draggedIcon.element.style.left =
        (event.clientX + window.draggedIcon.offset[0]) + 'px';
    draggedIcon.element.style.top =
        (event.clientY + window.draggedIcon.offset[1]) + 'px';
    draggedIcon.element.style.visibility = 'visible';
    draggedIcon.element = null;

    if (e.stopPropagation) { e.stopPropagation(); }
    return false;
  }

  const icons = document.querySelectorAll('.desktop .icon');
  for (const i of icons) {
    i.addEventListener('dragstart', dragStart, false);
    i.addEventListener('click', click, false);
  }

  document.body.addEventListener('dragover', dragOver, true);
  document.body.addEventListener('drop', drop, true);
</script>

谢谢!

1个回答

37
您需要防止默认操作
function drop(e) {
    if(e.preventDefault) { e.preventDefault(); }
    if(e.stopPropagation) { e.stopPropagation(); }
    window.draggedIcon.element.style.left = (event.clientX + window.draggedIcon.offset[0]) + 'px';
    window.draggedIcon.element.style.top  = (event.clientY + window.draggedIcon.offset[1]) + 'px';
    window.draggedIcon.element.style.visibility = 'visible';
    window.draggedIcon.element = null;
    return false;
}

4
preventDefault 能够完成任务!但是有人能解释一下为什么在 Firefox 上拖放会触发重定向吗? - Matthieu Riegler
猜测:将文件拖入Firefox中会导航到该文件,这就是默认导航到被拖动的URL的原因。在我的情况下,“拖动”之前调用了“event.dataTransfer.setData('text/plain',“css” )”,然后FF尝试打开URL“css”。 - awendt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接