4

如何使用 Javascript(在copy事件处理程序中)将图像放入剪贴板,就像通过右键单击浏览器中的图像并从上下文菜单中选择“复制图像”来完成一样。

脚本显示剪贴板内容的详细信息。对于复制的图像,它会打印:

DataTransfer { dropEffect: "none", effectAllowed: "uninitialized", items: DataTransferItemList[2], types: Array[2], files: FileList[1], mozItemCount: 1, mozCursor: "auto", mozUserCancelled: false, mozSourceNode: null }
DataTransferItem { kind: "string", type: "text/html" }
DataTransferItem { kind: "file", type: "image/png" }
Array [ "text/html", "Files" ]
File { name: "image.png", lastModified: 1504122845696, lastModifiedDate: Date 2017-08-30T19:54:05.696Z, webkitRelativePath: "", size: 385273, type: "image/png" }

所以这个问题可能可以重新表述——如何将文件附加到clipboardData事件copy处理函数中?

document.addEventListener('copy', (event) => {
  // event.clipboardData.?
  // maybe event.clipboardData.setData(?)
})

使用方法不工作演示。setData()

4

1 回答 1

2

//get reference to the div
var div = document.getElementById('someDiv');

//attach a paste event
div.addEventListener('paste', function(ev){
    var imgFile = null;
    var idx;
    var items = ev.clipboardData.items;
    for(idx=0;idx<items.length;idx++) {
        //check if any content is file
        if(items[idx].kind==="file") {
            //take that file to imgFile
            imgFile = items[idx].getAsFile();
            break;
        }
    }
    if(imgFile==null) {return;}
    
    //create a File reader
    var reader = new FileReader();
    reader.onload = function() {
        //create an img DOM object
        var img = new Image();
        //reader.result is nothing but the Base64 representation
        img.src = reader.result;
        
        //operate the DOM, clear the div and append the img
        div.innerHTML = '';
        div.appendChild(img);
    }
    //read that file using the reader
    reader.readAsDataURL(imgFile);
});
<div id="someDiv" style="min-width: 200px;min-height: 200px; border: 1px solid red">
Paste an image here (using Ctrl + V)

</div>

于 2017-08-30T21:48:37.980 回答