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

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

    @tyler's answer is the best! I have upvoted it. After spending so many hours I got that suggestion working exactly as intended.

    $(document).on('dragstart dragenter dragover', function(event) {    
        // Only file drag-n-drops allowed, http://jsfiddle.net/guYWx/16/
        if ($.inArray('Files', event.originalEvent.dataTransfer.types) > -1) {
            // Needed to allow effectAllowed, dropEffect to take effect
            event.stopPropagation();
            // Needed to allow effectAllowed, dropEffect to take effect
            event.preventDefault();
    
            $('.dropzone').addClass('dropzone-hilight').show();     // Hilight the drop zone
            dropZoneVisible= true;
    
            // http://www.html5rocks.com/en/tutorials/dnd/basics/
            // http://api.jquery.com/category/events/event-object/
            event.originalEvent.dataTransfer.effectAllowed= 'none';
            event.originalEvent.dataTransfer.dropEffect= 'none';
    
             // .dropzone .message
            if($(event.target).hasClass('dropzone') || $(event.target).hasClass('message')) {
                event.originalEvent.dataTransfer.effectAllowed= 'copyMove';
                event.originalEvent.dataTransfer.dropEffect= 'move';
            } 
        }
    }).on('drop dragleave dragend', function (event) {  
        dropZoneVisible= false;
    
        clearTimeout(dropZoneTimer);
        dropZoneTimer= setTimeout( function(){
            if( !dropZoneVisible ) {
                $('.dropzone').hide().removeClass('dropzone-hilight'); 
            }
        }, dropZoneHideDelay); // dropZoneHideDelay= 70, but anything above 50 is better
    });
    

提交回复
热议问题