How to detect the dragleave event in Firefox when dragging outside the window

后端 未结 5 1540
借酒劲吻你
借酒劲吻你 2020-12-04 10:31

Firefox doesn\'t properly trigger the dragleave event when dragging outside of the window:

https://bugzilla.mozilla.org/show_bug.cgi?id=665704

https://bugzil

相关标签:
5条回答
  • 2020-12-04 11:15

    Depending on what you wish to accomplish you can get around this issue by using the :-moz-drag-over pseudo-class that is only available in Firefox which lets you react to a file being dragged over an element.

    Take a look at this simple demo http://codepen.io/ryanseddon/pen/Ccsua

    .dragover {
        background: red;
        width: 500px;
        height: 300px;
    }
    .dragover:-moz-drag-over {
        background: green;
    }
    
    0 讨论(0)
  • 2020-12-04 11:17

    I've found a solution. The problem was not so much that the dragleave event wasn't firing; rather, the dragenter event was firing twice when first dragging a file into the window (and additionally sometimes when dragging over certain elements). My original solution was to use a counter to track when the final dragleave event was occuring, but the double firing of dragenter events was messing up the count. (Why couldn't I just listen for dragleave you ask? Well, because dragleave functions very similarly to mouseout in that it fires not only when leaving the element but also when entering a child element. Thus, when dragleave fires, your mouse may very well still be within the bounds of the original element.)

    The solution I came up with was to keep track of which elements dragenter and dragleave had been triggered on. Since events propagate up to the document, listening for dragenter and dragleave on a particular element will capture not only events on that element but also events on its children.

    So, I created a jQuery collection $() to keep track of what events were fired on what elements. I added the event.target to the collection whenever dragenter was fired, and I removed event.target from the collection whenever dragleave happened. The idea was that if the collection were empty it would mean I had actually left the original element because if I were entering a child element instead, at least one element (the child) would still be in the jQuery collection. Lastly, when the drop event is fired, I want to reset the collection to empty, so it's ready to go when the next dragenter event occurs.

    jQuery also saves a lot of extra work because it automatically does duplicate checking, so event.target doesn't get added twice, even when Firefox was incorrectly double-invoking dragenter.

    Phew, anyway, here's a basic version of the code I ended up using. I've put it into a simple jQuery plugin if anyone else is interested in using it. Basically, you call .draghover on any element, and draghoverstart is triggered when first dragging into the element, and draghoverend is triggered once the drag has actually left it.

    // The plugin code
    $.fn.draghover = function(options) {
      return this.each(function() {
    
        var collection = $(),
            self = $(this);
    
        self.on('dragenter', function(e) {
          if (collection.length === 0) {
            self.trigger('draghoverstart');
          }
          collection = collection.add(e.target);
        });
    
        self.on('dragleave drop', function(e) {
          collection = collection.not(e.target);
          if (collection.length === 0) {
            self.trigger('draghoverend');
          }
        });
      });
    };
    
    // Now that we have a plugin, we can listen for the new events 
    $(window).draghover().on({
      'draghoverstart': function() {
        console.log('A file has been dragged into the window.');
      },
      'draghoverend': function() {
        console.log('A file has been dragged out of window.');
      }
    });
    

    Without jQuery

    To handle this without jQuery you can do something like this:

    // I want to handle drag leaving on the document
    let count = 0
    onDragEnter = (event) => {
      if (event.currentTarget === document) {
        count += 1
      }
    }
    
    onDragLeave = (event) => {
      if (event.currentTarget === document) {
         count += 0
      }
    
      if (count === 0) {
        // Handle drag leave.
      }
    }
    
    0 讨论(0)
  • 2020-12-04 11:22

    Inspired by @PhilipWalton 's code, I simplified the jQuery plugin code.

    $.fn.draghover = function(fnIn, fnOut) {
        return this.each(function() {
            var n = 0;
            $(this).on('dragenter', function(e) {
                (++n, n==1) && fnIn && fnIn.call(this, e);
            }).on('dragleave drop', function(e) {
                (--n, n==0) && fnOut && fnOut.call(this, e);
            });
        });
    };
    

    Now you can use the jquery plugin like jquery hover method:

    // Testing code 1
    $(window).draghover(function() {
        console.log('into window');
    }, function() {
        console.log('out of window');
    });
    
    // Testing code 2
    $('#d1').draghover(function() {
        console.log('into #d1');
    }, function() {
        console.log('out of #d1');
    });
    
    0 讨论(0)
  • 2020-12-04 11:32

    only solution that has worked for me and took me a few goes hope this helps someone!

    note when cloning you need to deepclone with events and data:

    HTML:

    <div class="dropbox"><p>Child element still works!</p></div>
    
    <div class="dropbox"></div>
    
    <div class="dropbox"></div>
    

    jQuery

    $('.dropbox').each(function(idx, el){
        $(this).data("counter" , 0);
    });
    
    $('.dropbox').clone(true,true).appendTo($('body');
    
    $('dropbox').on({
        dragenter : function(e){
            $(this).data().counter++;
            <!-- YOUR CODE HERE -->
        },
          dragleave: function(e){
    
            $(this).data().counter--;
    
             if($(this).data().counter === 0)
                  <!-- THEN RUN YOUR CODE HERE -->
        }
    });
    
    0 讨论(0)
  • 2020-12-04 11:32
    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            // stop your drag event here
            // for now we can just use an alert
            alert("left window");
        }
    });
    

    This is copied from How can I detect when the mouse leaves the window?. addEvent is just crossbrowser addEventListener.

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