监听粘贴事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** 粘贴上传图片 **/ document.getElementsByTagName( "textarea" )[0].addEventListener( 'paste' , function (e) { var clipboard = e.clipboardData; for ( var i=0,len=clipboard.items.length; i<len; i++) { if (clipboard.items[i].kind == 'file' || clipboard.items[i].type.indexOf( 'image' ) > -1) { var imageFile = clipboard.items[i].getAsFile(); var form = new FormData; form.append( 't' , 'ajax-uploadpic' ); form.append( 'avatar' , imageFile); var callback = G.uploadpicCallback || function (type, data){}; $.ajax({ url: G.ROOT_URL+ 'sys/ajax' , type: "POST" , data: form, processData: false , contentType: false , beforeSend: function () { callback( 'before' ); }, error: function () { callback( 'error' ); }, success: function (url) { callback( 'success' , url); } }) e.preventDefault(); } } }); |
其中只对textarea
标签绑定粘贴事件,还调用了一个全局函数G.uploadpicCallback
,使用上是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | G = {}; G.uploadpicCallback = function (type, src){ type = type || 'before' ; var $the = $( '#content' ); switch (type){ // 开始上传 case 'before' : $the.attr( 'disabled' , 'disabled' ); break ; // 服务器返回错误 case 'error' : $the.attr( 'disabled' , false ); alert( '图片上传失败' ); break ; // 上传成功 case 'success' : $the.attr( 'disabled' , false ); $the.val($the.val()+ '<img src="' +src+ '" width="100%">' ); break ; } } |