1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>onpaste event example</title> 6 </head> 7 <body id="editor" onpaste="pasteIntercept(event)"> 8 9 <h2>日志</h2> 10 <textarea rows="15" cols="80" id="log" readonly="true"></textarea> 11 <div> 12 <img src="" id="img" alt=""> 13 </div> 14 15 16 <script> 17 function log(txt) { 18 document.getElementById("log").appendChild(document.createTextNode(txt + " ")); 19 } 20 21 /* 22 在网页粘贴图片 23 1.监听paste事件 24 2.创建FileReader对象读取图像数据 25 3.发送数据到后台返回图片地址 26 4.将图片地址显示图片 27 */ 28 29 function pasteIntercept(d) { 30 log("粘贴!"); 31 var obj = { 32 data:'' 33 } 34 for (var b = 0; b < d.clipboardData.items.length; b++) { 35 var c = d.clipboardData.items[b]; 36 if (c.type == "image/png") { 37 obj.mode = 1; 38 var a = new FileReader(); 39 a.onloadend = function () { 40 obj.data = this.result.substr(this.result.indexOf(",") + 1); 41 img.src='data:image/png;base64,' + obj.data; 42 43 }; 44 a.readAsDataURL(c.getAsFile()); 45 46 break; 47 } 48 } 49 50 } 51 52 // document.getElementById("editor").addEventListener("paste", pasteIntercept, false); 53 </script> 54 </body> 55 </html>