How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

后端 未结 12 938
醉话见心
醉话见心 2020-12-13 20:16

I\'d like to be able to highlight the drop area as soon as the cursor carrying a file enters the browser window, exactly the way Gmail does it. But I can\'t make it work, an

12条回答
  •  庸人自扰
    2020-12-13 20:42

    Adding the events to document seemed to work? Tested with Chrome, Firefox, IE 10.

    The first element that gets the event is , which should be ok I think.

    var dragCount = 0,
        dropzone = document.getElementById('dropzone');
    
    function dragenterDragleave(e) {
      e.preventDefault();
      dragCount += (e.type === "dragenter" ? 1 : -1);
      if (dragCount === 1) {
        dropzone.classList.add('drag-highlight');
      } else if (dragCount === 0) {
        dropzone.classList.remove('drag-highlight');
      }
    };
    
    document.addEventListener("dragenter", dragenterDragleave);
    document.addEventListener("dragleave", dragenterDragleave);
    

提交回复
热议问题