我们做了一个非常简单的html编辑器(contenteditable="true"
),用户可以粘贴从其他网页复制的图片,但是如果用户从word中复制图片,word会粘贴src 为 file://temp/someimg.jpg 浏览器将不会加载图像。
<img src="file://..../.jgp">
但如果我在我的开发计算机 (http://127.0.0.1) 上运行该网页并执行相同操作,word 会将图像 src 粘贴为“data:image/jpeg;base64.....”
有什么方法可以让 word 始终将 base64 编码的图片粘贴到编辑器,而不仅仅是 file://位置?
最佳答案
您将需要处理粘贴事件并读取图像内容的剪贴板。请在下面的代码片段中找到原型(prototype)(在谷歌浏览器中测试),它展示了相同的内容。
// create paste event listener
window.addEventListener("paste", pasteHandler);
// handle paste events
function pasteHandler(e) {
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
for (var i in items) { // iterate through clipbord items
var item = items[i];
if (item.kind == "file") { //image is a file
// create image source
var blob = item.getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
var pastedImage = new Image();
pastedImage.src = source;
// add it in editor
document.getElementById("editor").innerHTML = document.getElementById("editor").innerHTML + pastedImage.outerHTML;
}
}
}
}
}
#editor{
min-width: 400px;
min-height: 250px;
border: solid;
border-width: thin;
padding: 10px;
}
<div id="editor" contenteditable=true>Copy an image from word<br/>Press Ctrl+v to paste it here <br/></div>
关于javascript - HTML 编辑器和从 Word 粘贴图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469678/