Prevent browser from loading a drag-and-dropped file

前端 未结 10 2022
逝去的感伤
逝去的感伤 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: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])
    );
    

提交回复
热议问题