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

后端 未结 12 904
醉话见心
醉话见心 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:37

    Your third argument to addEventListener is true, which makes the listener run during capture phase (see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow for a visualization). This means that it will capture the events intended for its descendants - and for the body that means all elements on the page. In your handlers, you'll have to check if the element they're triggered for is the body itself. I'll give you my very dirty way of doing it. If anyone knows a simpler way that actually compares elements, I'd love to see it.

    this.dragenter = function() {
        if ($('body').not(this).length != 0) return;
        ... functional code ...
    }
    

    This finds the body and removes this from the set of elements found. If the set isn't empty, this wasn't the body, so we don't like this and return. If this is body, the set will be empty and the code executes.

    You can try with a simple if (this == $('body').get(0)), but that will probably fail miserably.

    0 讨论(0)
  • 2020-12-13 20:41

    I see a lot of overengineered solutions out there. You should be able to achieve this by simply listening to dragenter and dragleave as your gut seemingly told you.

    The tricky part is that when dragleave fires, it seems to have its toElement and fromElement inverted from what makes sense in everyday life (which kind of makes sense in logical terms since it's the inverted action of dragenter). Bottom-line when you move the cursor from the listening element to outside that element, toElement will have the listening element and fromElement will have the outer non-listening element. In our case, fromElement will be null when we drag outside the browser.

    Solution

    window.addEventListener("dragleave", function(e){
      if (!e.fromElement){
        console.log("Dragging back to OS")
      }
    })
    
    window.addEventListener("dragenter", function(e){
      console.log("Dragging to browser")
    })
    
    0 讨论(0)
  • 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 <html>, 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);
    
    0 讨论(0)
  • 2020-12-13 20:42

    really sorry to post something that is angular & underscore specific, however the way i solved the problem (HTML5 spec, works on chrome) should be easy to observe.

    .directive('documentDragAndDropTrigger', function(){
    return{
      controller: function($scope, $document){
    
        $scope.drag_and_drop = {};
    
        function set_document_drag_state(state){
          $scope.$apply(function(){
            if(state){
              $document.context.body.classList.add("drag-over");
              $scope.drag_and_drop.external_dragging = true;
            }
            else{
              $document.context.body.classList.remove("drag-over");
              $scope.drag_and_drop.external_dragging = false;
            }
          });
        }
    
        var drag_enters = [];
        function reset_drag(){
          drag_enters = [];
          set_document_drag_state(false);
        }
        function drag_enters_push(event){
          var element = event.target;
          drag_enters.push(element);
          set_document_drag_state(true);
        }
        function drag_leaves_push(event){
          var element = event.target;
          var position_in_drag_enter = _.find(drag_enters, _.partial(_.isEqual, element));
          if(!_.isUndefined(position_in_drag_enter)){
            drag_enters.splice(position_in_drag_enter,1);
          }
          if(_.isEmpty(drag_enters)){
            set_document_drag_state(false);
          }
        }
    
        $document.bind("dragenter",function(event){
          console.log("enter", "doc","drag", event);
          drag_enters_push(event);
        });
    
        $document.bind("dragleave",function(event){
          console.log("leave", "doc", "drag", event);
          drag_leaves_push(event);
          console.log(drag_enters.length);
        });
    
        $document.bind("drop",function(event){
          reset_drag();
          console.log("drop","doc", "drag",event);
        });
      }
    };
    

    })

    I use a list to represent the elements that have triggered a drag enter event. when a drag leave event happens i find the element in the drag enter list that matches, remove it from the list, and if the resulting list is empty i know that i have dragged outside of the document/window.

    I need to reset the list containing dragged over elements after a drop event occurs, or the next time I start dragging something the list will be populated with elements from the last drag and drop action.

    I have only tested this on chrome so far. I made this because Firefox and chrome have different API implementations of HTML5 DND. (drag and drop).

    really hope this helps some people.

    0 讨论(0)
  • 2020-12-13 20:45

    Here's another solution. I wrote it in React, but I'll explain it at the end if you want to rebuild it in plain JS. It's similar to other answers here, but perhaps slightly more refined.

    import React from 'react';
    import styled from '@emotion/styled';
    import BodyEnd from "./BodyEnd";
    
    const DropTarget = styled.div`
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        pointer-events: none;
        background-color:rgba(0,0,0,.5);
    `;
    
    function addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions) {
        document.addEventListener(type, listener, options);
        return () => document.removeEventListener(type, listener, options);
    }
    
    function setImmediate(callback: (...args: any[]) => void, ...args: any[]) {
        let cancelled = false;
        Promise.resolve().then(() => cancelled || callback(...args));
        return () => {
            cancelled = true;
        };
    }
    
    function noop(){}
    
    function handleDragOver(ev: DragEvent) {
        ev.preventDefault();
        ev.dataTransfer!.dropEffect = 'copy';
    }
    
    
    export default class FileDrop extends React.Component {
    
        private listeners: Array<() => void> = [];
    
        state = {
            dragging: false,
        }
    
        componentDidMount(): void {
            let count = 0;
            let cancelImmediate = noop;
    
            this.listeners = [
                addEventListener('dragover',handleDragOver),
                addEventListener('dragenter',ev => {
                    ev.preventDefault();
    
                    if(count === 0) {
                        this.setState({dragging: true})
                    }
                    ++count;
                }),
                addEventListener('dragleave',ev => {
                    ev.preventDefault();
                    cancelImmediate = setImmediate(() => {
                        --count;
                        if(count === 0) {
                            this.setState({dragging: false})
                        }
                    })
    
                }),
                addEventListener('drop',ev => {
                    ev.preventDefault();
                    cancelImmediate();
                    if(count > 0) {
                        count = 0;
                        this.setState({dragging: false})
                    }
                }),
            ]
        }
    
        componentWillUnmount(): void {
            this.listeners.forEach(f => f());
        }
    
    
        render() {
            return this.state.dragging ? <BodyEnd><DropTarget/></BodyEnd> : null;
        }
    }
    

    So, as others have observed, the dragleave event fires before the next dragenter fires, which means our counter will momentarily hit 0 as we drag files (or whatever) around the page. To prevent that, I've used setImmediate to push the event to the bottom of JavaScript's event queue.

    setImmediate isn't well supported, so I wrote my own version which I like better anyway. I haven't seen anyone else implement it quite like this. I use Promise.resolve().then to move the callback to the next tick. This is faster than setImmediate(..., 0) and simpler than many of the other hacks I've seen.

    Then the other "trick" I do is to clear/cancel the leave event callback when you drop a file just in case we had a callback pending -- this will prevent the counter from going into the negatives and messing everything up.

    That's it. Seems to work very well in my initial testing. No delays, no flashing of my drop target.


    Can get the file count too with ev.dataTransfer.items.length

    0 讨论(0)
  • 2020-12-13 20:45

    I found out from looking at the spec that if the evt.dataTransfer.dropEffect on dragEnd match none then it's a cancelation.

    I did already use that event to handle copying without affecting the clipboard. so this was good for me.
    When I hit Esc then the drop effect was equal to none

    window.ondragend = evt => {
      if (evt.dataTransfer.dropEffect === 'none') abort
      if (evt.dataTransfer.dropEffect === 'copy') copy // user holds alt on mac
      if (evt.dataTransfer.dropEffect === 'move') move 
    }
    
    0 讨论(0)
提交回复
热议问题