<html>
<head>
<title>test chrome paste image</title>
<style>
#non-editable img{
width: 300px;
}
#editable {
margin-top: 20px;
width: 400px;
height: 300px;
border: 1px dashed blue;
}
#editable img{
width: 300px;
}
</style>
</head>
<body>
<h2>在浏览器中测试图像粘贴</h2>
<div id="non-editable">
<p>复制下面的img,然后粘贴到下面的区域</p>
<img
src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594274150060&di=2aa0fa4d85cb448430e9dcc27db1d9e9&imgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F14%2F75%2F01300000164186121366756803686.jpg" />
</div>
<div id="editable" contenteditable="true">
<p>这是一个可编辑的div区域</p>
<p>将图像粘贴到这里。</p>
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function() {
function paste_img(e) {
if (e.clipboardData.items) {
// google-chrome
console.log('support clipboard Data items(谷歌浏览器 ...)');
ele = e.clipboardData.items
for (var i = 0; i < ele.length; ++i) {
if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -1) {
var blob = ele[i].getAsFile();
window.URL = window.URL || window.webkitURL;
var blobUrl = window.URL.createObjectURL(blob);
console.log(blobUrl);
var new_img = document.createElement('img');
new_img.setAttribute('src', blobUrl);
var new_img_intro = document.createElement('p');
new_img_intro.innerHTML =
'粘贴的img url: <br /><a target="_blank" href="' + blobUrl +
'">' + blobUrl + '</a>';
document.getElementById('editable').appendChild(new_img);
document.getElementById('editable').appendChild(new_img_intro);
}
}
} else {
alert('non-chrome');
}
}
document.getElementById('editable').onpaste = function() {
paste_img(event);
return false;
};
}
</script>
以上代码,复制粘贴即可运行。