Accept drag & drop of image from another browser window

前端 未结 6 1976
夕颜
夕颜 2020-12-23 09:44

In Javascript, I know how to set up a drag & drop target that accepts file uploads from the user\'s computer. How can I set up a drop target that accepts images that are

6条回答
  •  没有蜡笔的小新
    2020-12-23 10:18

    You could define a drop zone:

    DropZone => you could drop any image from any page here

    and then handle the dragenter, dragexit, dragover and drop events:

    var dropbox = document.getElementById('dropbox');
    
    dropbox.addEventListener('dragenter', noopHandler, false);
    dropbox.addEventListener('dragexit', noopHandler, false);
    dropbox.addEventListener('dragover', noopHandler, false);
    dropbox.addEventListener('drop', drop, false);
    
    function noopHandler(evt) {
        evt.stopPropagation();
        evt.preventDefault();
    }
    function drop(evt) {
        evt.stopPropagation();
        evt.preventDefault(); 
        var imageUrl = evt.dataTransfer.getData('Text');
        alert(imageUrl);
    }
    

    ​ It is inside the drop event handler that we are reading the image data from the dataTransfer object as Text. If we dropped an image from some other webpage this text will represent the url of the image.

    And here's a live demo.


    UPDATE:

    It looks like there are differences between Chrome on Windows and MacOS. On Windows dataTransfer.getData('Text'); works but not on MacOS. dataTransfer.getData('URL'); should work on both.

提交回复
热议问题