Prevent browser from loading a drag-and-dropped file

前端 未结 10 1974
逝去的感伤
逝去的感伤 2020-11-28 02:12

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

相关标签:
10条回答
  • 2020-11-28 02:33

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

    window.addEventListener("dragover",function(e){
      e = e || event;
      e.preventDefault();
    },false);
    window.addEventListener("drop",function(e){
      e = e || event;
      e.preventDefault();
    },false);
    
    0 讨论(0)
  • 2020-11-28 02:35

    To build on the "check the target" method outlined in a few other answers, here is a more generic/functional method:

    function preventDefaultExcept(predicates) {
      return function (e) {
        var passEvery = predicates.every(function (predicate) { return predicate(e); })
        if (!passEvery) {
          e.preventDefault();
        }
      };
    }
    

    Called like:

    function isDropzone(e) { return e.target.id === 'dropzone'; }
    function isntParagraph(e) { return e.target.tagName !== 'p'; }
    
    window.addEventListener(
      'dragover',
      preventDefaultExcept([isDropzone, isntParagraph])
    );
    window.addEventListener(
      'drop',
      preventDefaultExcept([isDropzone])
    );
    
    0 讨论(0)
  • 2020-11-28 02:37

    To allow drag-and-drop only on some elements, you could do something like:

    window.addEventListener("dragover",function(e){
      e = e || event;
      console.log(e);
      if (e.target.tagName != "INPUT") { // check which element is our target
        e.preventDefault();
      }
    },false);
    window.addEventListener("drop",function(e){
      e = e || event;
      console.log(e);
      if (e.target.tagName != "INPUT") {  // check which element is our target
        e.preventDefault();
      }  
    },false);
    
    0 讨论(0)
  • 2020-11-28 02:41

    try this:

    document.body.addEventListener('drop', function(e) {
        e.preventDefault();
    }, false);
    
    0 讨论(0)
提交回复
热议问题