Prevent browser from loading a drag-and-dropped file

2022-08-30 01:01:14

I'm adding an html5 drag and drop uploader to my page.

When a file is dropped into the upload area, everything works great.

However, if I accidentally drop the file outside of the upload area, the browser loads the local file as if it is a new page.

How can I prevent this behavior?

Thanks!


答案 1

You can add a event listener to the window that calls on all dragover and drop events.
Example:preventDefault()

window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);

答案 2

After a lot of fiddling around, I found this to be the stablest solution:

var dropzoneId = "dropzone";

window.addEventListener("dragenter", function(e) {
  if (e.target.id != dropzoneId) {
    e.preventDefault();
    e.dataTransfer.effectAllowed = "none";
    e.dataTransfer.dropEffect = "none";
  }
}, false);

window.addEventListener("dragover", function(e) {
  if (e.target.id != dropzoneId) {
    e.preventDefault();
    e.dataTransfer.effectAllowed = "none";
    e.dataTransfer.dropEffect = "none";
  }
});

window.addEventListener("drop", function(e) {
  if (e.target.id != dropzoneId) {
    e.preventDefault();
    e.dataTransfer.effectAllowed = "none";
    e.dataTransfer.dropEffect = "none";
  }
});
<div id="dropzone">...</div>

Setting both and unconditionally on the window causes my drop zone not to accept any d-n-d any longer, regardless whether the properties are set new or not.effectAllowdropEffect