我正在尝试通过用户将 Ctrl+V 粘贴到 div #pasteImageDiv
中来保存图像/屏幕截图。它在 Chrome 上运行良好,但在 IE 上运行不佳。
我正在使用 IE10。
到目前为止,我发现如果我将任何文本粘贴到 div #pasteImageDiv,它会正确捕获 onpaste
事件,即使在 IE 中也是如此。
但是,如果我粘贴图像而不是文本,它甚至不会捕获 onpaste
(IE 甚至不会进入处理 onpaste
事件的函数)。
document.getElementById('pasteImageDiv').onpaste = function (event) {
无论我粘贴文本字符串还是图像,它在 Chrome 中都运行良好。 我希望你明白我面临什么样的问题。不过,如果需要任何其他信息,请告诉我。
$('#pasteImageHere, #pasteImageDiv').click(function(e){ //on paste image button click
e.preventDefault();
$('#hideOnPaste').hide();
//document.getElementById('pasteImageDiv').click();
document.getElementById('pasteImageDiv').style.backgroundColor = "#F1F1F1";
document.getElementById('pasteImageDiv').onpaste = function (event) {
$('#hideOnPaste').hide();
//console.log(event.clipboardData.getData('image/png'));
// use event.originalEvent.clipboard for newer chrome versions
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
// find pasted image among pasted items
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result); // data url!
var elem = document.createElement("img");
elem.setAttribute("id", "pastedImage");
elem.setAttribute("height", "200");
elem.setAttribute("width", "300");
document.getElementById("pasteImageDiv").appendChild(elem);
document.getElementById("pastedImage").src = event.target.result;
document.getElementById('inputImageData').value = event.target.result;
console.log($('#inputImageData').val());
$('#pastedImage').css('width', '300px');
$('#pastedImage').css('height', '200px');
document.getElementById("pastedImage").style.height = '200px';
};
reader.readAsDataURL(blob);
$('#removePastedImage').show();
}
}
});
最佳答案
在 IE11 中添加了图像粘贴支持:
Starting with IE11, images pasted from the clipboard are base64 encoded by default. Users can now easily and safely copy and paste images from their local file system into contenteditable regions of a website. Prior to IE11, pasting a local image on a live website (across security zones) resulted in a broken image icon, as a security measure to prevent local file access.
IE11 is the first browser that supports both pasting images directly from clipboard (for example, from photo editing software or from PrintScreen) and pasting HTML that incorporates local images (for example, from applications such as Microsoft Office that store images temporarily in local paths). Either DataURI or Blob can be used to encode these images.
引用资料
关于javascript - 使用 Javascript onpaste 粘贴图像不适用于 IE,适用于 chrome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37885605/