1.1 监听onpaste事件
1.1.1 定义和用法
npaste 事件在用户向元素中粘贴文本时触发。
注意: 虽然使用的 HTML 元素都支持 onpaste 事件,但实际上并非支持所有元素,例如
元素, 除非设置了 contenteditable 为 "true" (查看下文的更多实例)。
提示: onpaste 事件通常用于 type="text" 的 元素。
提示: 有三种方式可以在元素中粘贴内容:
1》按下 CTRL + V
2》从浏览器的编辑菜单中选择 "Paste(粘贴)"
3》右击鼠标按钮在上下文菜单中选择 "Paste(粘贴)" 命令。
1.1.2 语法
HTML 中:
JavaScript 中:
object.οnpaste=function(){ myScript};
JavaScript 中, 使用 addEventListener() 方法:
object.addEventListener("paste", myScript);
注意: Internet Explorer 8 及更早 IE 版本不支持 addEventListener() 方法。
当向
元素上粘贴文本内容时执行 JavaScript (注意 contenteditable 设置为 "true"):
尝试在段落中粘贴内容。
1.1.3 event.clipboardData
通过事件回调中的event参数,获取剪贴板数据event.clipboardData(不是所有的浏览器都支持)
// '/image/.test(event.clipboardData.types)' // 检查是否为图片
// 获取图片二进制数据(似乎浏览器的实现都会有大小差异)
Array.each(event.clipboardData.items,function(item){
if(/image/.test(item.type)) {
varblob = item.getAsFile();
varURL =window.URL ||window.webkitURL;
varsource = URL.createObjectURL(blob);
console.log(source)
}
});
通过Ajax将数据发送到后端服务器,后端将图片存储起来后,返回一个图片可访问地址
访问这个地址就可以看到图片了
1.2 使用样例
1》绑定单个元素事件
window.addEvent("paste",function(e){ });
test chrome paste imagetitle>}
style>
window.onload=function() {functionpaste_img(e) {debugger;if( e.clipboardData.items ) {//google-chrome
alert('support clipboardData.items(chrome ...)');
ele=e.clipboardData.itemsfor(vari= 0; i
window.URL=window.URL||window.webkitURL;varblobUrl=window.URL.createObjectURL(blob);
console.log(blobUrl);varnew_img=document.createElement('img');
new_img.setAttribute('src', blobUrl);varnew_img_intro=document.createElement('p');
new_img_intro.innerHTML= 'the pasted img url(open it in new tab):
' +blobUrl+ '">' +blobUrl+ '';
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>
head>
test image paste in browserh2>
copy the following img, then paste it into the area belowp>
div>
this is an editable div areap>
paste the image into here.p>
div>
body>
html>
2》遍历循环所有的事件