1.1 監聽onpaste事件
1.1.1 定義和用法
npaste 事件在用戶向元素中粘貼文本時觸發。
注意: 雖然使用的 HTML 元素都支持 onpaste 事件,但實際上並非支持所有元素,例如 <p> 元素, 除非設置了 contenteditable 為 "true" (查看下文的更多實例)。
提示: onpaste 事件通常用於 type="text" 的 <input> 元素。
提示: 有三種方式可以在元素中粘貼內容:
1》按下 CTRL + V
2》從瀏覽器的編輯菜單中選擇 "Paste(粘貼)"
3》右擊鼠標按鈕在上下文菜單中選擇 "Paste(粘貼)" 命令。
1.1.2 語法
HTML 中:
<element onpaste="myScript">
JavaScript 中:
object.onpaste=function(){myScript};
JavaScript 中, 使用 addEventListener() 方法:
object.addEventListener("paste", myScript);
注意: Internet Explorer 8 及更早 IE 版本不支持 addEventListener() 方法。
當向 <p> 元素上粘貼文本內容時執行 JavaScript (注意 contenteditable 設置為 "true"):
<p contenteditable="true" onpaste="myFunction()">嘗試在段落中粘貼內容。</p>
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)) {
var blob = item.getAsFile();
varURL =
window.URL ||
window.webkitURL;
var source = URL.createObjectURL(blob);
console.log(source)
}
});
通過Ajax將數據發送到后端服務器,后端將圖片存儲起來后,返回一個圖片可訪問地址
訪問這個地址就可以看到圖片了
1.2 使用樣例
1》綁定單個元素事件
window.addEvent("paste",function(e){ });
<html> <head> <title>test chrome paste image</title> <style> DIV#editable { width: 400px; height: 300px; border: 1px dashed blue; } </style> <script type="text/javascript"> window.onload=function() { function paste_img(e) { debugger; if ( e.clipboardData.items ) { // google-chrome alert('support clipboardData.items(chrome ...)'); 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 = 'the pasted img url(open it in new tab): <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> </head> <body > <h2>test image paste in browser</h2> <div id="non-editable" > <p>copy the following img, then paste it into the area below</p> <img src="./128.png" /> </div> <div id="editable" contenteditable="true" > <p>this is an editable div area</p> <p>paste the image into here.</p> </div> </body> </html>
2》遍歷循環所有的事件