HTML5 drop event doesn't work unless dragover is handled

后端 未结 4 1069
一生所求
一生所求 2020-12-02 16:51

I am listening to the drop event and doing e.preventDefault() But its trying to open the dropped file. It was working fine till yesterday. But just

相关标签:
4条回答
  • 2020-12-02 17:32

    I guess it is because that without dragOver event handler, default event handler of dragOver event is used, thus, no drop event is triggered after that. There is a need with e.preventDefault for dragOver event before drop event.

    0 讨论(0)
  • 2020-12-02 17:32

    I'm not sure if I understand your problem correctly but if you want to read dropped files you need to handle dragover event and put there at least this line of code:

    evt.dataTransfer.dropEffect = 'copy';
    

    otherwise dropEffect is null by default and you won't get any data.

    0 讨论(0)
  • 2020-12-02 17:52

    https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations

    If you want to allow a drop, you must prevent the default handling by cancelling the event. You can do this either by returning false from an attribute-defined event listener, or by calling the event's event.preventDefault method. The latter may be more feasible in a function defined in a separate script.

    <div ondragover="return false">
    <div ondragover="event.preventDefault()">
    

    Calling the preventDefault method during both a dragenter and dragover event will indicate that a drop is allowed at that location. However, you will commonly wish to call the preventDefault method only in certain situations, for example, only if a link is being dragged. To do this, call a function which checks a condition and only cancels the event when the condition is met. If the condition is not met, don't cancel the event, and a drop will not occur there if the user releases the mouse button.

    https://developer.mozilla.org/en-US/docs/Web/Events/dragover

      /* events fired on the drop targets */
      document.addEventListener("dragover", function( event ) {
          // prevent default to allow drop
          event.preventDefault();
      }, false);
    
    0 讨论(0)
  • 2020-12-02 17:52

    Works fine for me. Are you loading this as an HTTP or a FILE URL? I believe it needs to be an HTTP URL with Chrome.

    0 讨论(0)
提交回复
热议问题