简体   繁体   English

HTML5 DragNDrop - Drop 事件永远不会触发

[英]HTML5 DragNDrop - Drop event never fires

I'm trying to implement a drag'n'drop upload input for a web app.我正在尝试为 Web 应用程序实现拖放式上传输入。 Detecting drag start and end and appropriate drop target styling works flawlessly, though as soon as I drop an image file on the target, it opens in the browser.检测拖动开始和结束以及适当的放置目标样式可以完美地工作,但一旦我将图像文件放在目标上,它就会在浏览器中打开。 I know this has been asked pretty often on Stack Overflow, but I couldn't find a solution anywhere yet.我知道在 Stack Overflow 上经常有人问这个问题,但我在任何地方都找不到解决方案。

What I do see is: Listeners for dragenter , dragstart and dragend fire correctly, while drop does not.我看到的是: dragenterdragstartdragend监听器正确触发,而drop没有。 Please see the code below:请看下面的代码:

(Note: The app object is just a simple, custom abstraction object, nothing special about it. The app.on method calls addEventListener and attaches the event wrapped in a try-catch block.) (注意: app对象只是一个简单的、自定义的抽象对象,没有什么特别之处app.on方法调用addEventListener并附加包装在 try-catch 块中的事件。)


Attaching the events附加事件

app.on('drag dragover dragstart', app.elements.pictureDropArea, app.events.startedDragging, true);
app.on('dragenter', app.elements.pictureDropArea, app.events.isDragging);
app.on('dragleave dragend', app.elements.pictureDropArea, app.events.stoppedDragging);
app.on('drop', app.elements.pictureDropArea, app.events.isDropped);


The individual events个别事件

app.events.startedDragging = function(event) {
  event.preventDefault();
  event.stopPropagation();
  return false;
};

app.events.isDragging = function(event) {
  event.preventDefault();
  event.stopPropagation();
  app.elements.pictureDropArea.classList.add('dragged-over');
  return false;
};

app.events.stoppedDragging = function(event) {
  event.preventDefault();
  event.stopPropagation();
  app.elements.pictureDropArea.classList.remove('dragged-over');
  return false;
};

app.events.isDropped = function(event) {
  event.preventDefault();
  event.stopPropagation();
  console.log('drop event fired.');

  var file = event.dataTransfer.files[ 0 ];

  console.log(file);
  return false;
};

Found it accidentally when I applied the same events to the body .当我将相同的事件应用于body时意外发现它。 It seems like there needs to a listener for dragover on the document body with the usual preventDefault and stopPropagation stuff:好像有需要的侦听dragover在文档主体与通常preventDefaultstopPropagation东西:

app.on('dragover', document.body, function(event) {
  event.preventDefault();
  event.stopPropagation();
  return false;
});

God, I hate this API so much...天啊,我太讨厌这个API了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM