目前仅有高版本的 Chrome 浏览器支持这样直接粘贴,其他浏览器目前为止还无法粘贴,不过火狐和ie11浏览器在可编辑的div中能够粘贴截图的图片也是base64位和Chrome利用clipboardData的效果是一样的,只是在火狐和ie11浏览器中目前还无法实现类似用clipboardData直接获取图片的base64数据,它是自带的直接进去img数据
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>利用clipboardData在网页中实现截屏粘贴的功能</title>
<style type="text/css">
.box{ width:500px; height:300px; border:1px solid #ddd; }
.box img{max-width:480px; max-height: 100%; text-align: center;}
</style>
</head>
<body>
<div class="box" contenteditable="true" id="testInput">
</div>
<script type="text/javascript">
(function(){
var imgReader = function( item ){
var blob = item.getAsFile(),
reader = new FileReader();
reader.onload = function( e ){
var img = new Image();
img.src = e.target.result;
console.log(img);
document.getElementById('testInput').appendChild( img );
};
reader.readAsDataURL( blob );
};
document.getElementById( 'testInput' ).addEventListener( 'paste', function( e ){
//window.clipboardData.getData("Text") ie下获取黏贴的内容 e.clipboardData.getData("text/plain")火狐谷歌下获取黏贴的内容
//alert(e.clipboardData.getData("text/plain") )
var clipboardData = e.clipboardData,//谷歌
i = 0,
items, item, types;
console.log('0')
if( clipboardData ){
console.log('1')
items = clipboardData.items;
if( !items ){
console.log(2)
return;
}
console.log(3)
item = items[0];
types = clipboardData.types || [];
for( ; i < types.length; i++ ){
if( types[i] === 'Files' ){
item = items[i];
break;
}
}
if( item && item.kind === 'file' && item.type.match(/^image\//i) ){
imgReader( item );
}
}
},false);
})();
</script>
</script>
</body>
</html>