先不说复制,先说粘贴
demo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>复制图片demo</title>
</head>
<style>
* { margin: 0px;padding: 0px; }
.d0 {
margin: 0px auto;
width: 200px;height: 200px;
border: 1px solid red;
}
</style>
<script src="./jquery-3.2.1.min.js"></script>
<body>
<div contenteditable class="d0" id="d0"></div>
<div id="btn">按钮</div>
<img id="img" />
</body>
<script>
$(function() {
$("#d0").on("paste", function(e){
console.log(e)
var clipboardData = e.originalEvent.clipboardData;
var items = clipboardData.items || [];
var types = clipboardData.types || [];
console.log(types[0])
switch(types[0]) {
case 'Files':
var reader = new FileReader();
console.log(items[0].getAsFile())
reader.readAsDataURL(items[0].getAsFile());
reader.onload = function(){
$("#img").attr('src', reader.result);
};
break;
case 'text/html':
var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
var str = clipboardData.getData('text/html');
var arr = str.match(srcReg);
$("#img").attr('src', arr[1]);
break;
case 'text/plain':
$("#d0").html(clipboardData.getData('Text'));
break;
}
return false;
})
$("#btn").on("click", function() {
$("#d0").trigger("paste");
})
})
</script>
</html>
记得把JQ文件加载了。