How do I detect a file is being dragged rather than a draggable element on my page?

后端 未结 4 1681
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 01:30

I\'m using the html5 events to enable both file and element drag-and-drop. I\'ve attached the dragover event to the body and am using event delegations to show where a dragg

4条回答
  •  暖寄归人
    2020-12-29 02:14

    Use the function below to check if the drag source is an external file.

    Tested on Windows 7 with:

    • Firefox version 39
    • Chrome version 44
    • Safari version 5.1.7
    function isDragSourceExternalFile(dataTransfer){
        // Source detection for Safari v5.1.7 on Windows.
        if (typeof Clipboard != 'undefined') {
            if (dataTransfer.constructor == Clipboard) {
                if (dataTransfer.files.length > 0)
                    return true;
                else
                    return false;
            }
        }
    
        // Source detection for Firefox on Windows.
        if (typeof DOMStringList != 'undefined'){
            var DragDataType = dataTransfer.types;
            if (DragDataType.constructor == DOMStringList){
                if (DragDataType.contains('Files'))
                    return true;
                else
                    return false;
            }
        }
    
        // Source detection for Chrome on Windows.
        if (typeof Array != 'undefined'){
            var DragDataType = dataTransfer.types;
            if (DragDataType.constructor == Array){
                if (DragDataType.indexOf('Files') != -1)
                    return true;
                else
                    return false;
            }
        }
    }
    

    Example Usage with JQuery

    $(document).on('dragover', function(e){
        var IsFile = isDragSourceExternalFile(e.originalEvent.dataTransfer);
        console.log(IsFile);
    });
    

提交回复
热议问题