實時檢測 input、textarea輸入改變事件,支持低版本IE,支持復制粘貼
檢測input、textarea輸入改變事件有以下幾種:
1、onkeyup/onkeydown?捕獲用戶鍵盤輸入事件。
缺陷:復制粘貼時無法檢測
2、onchenge
缺陷:要滿足觸發條件:當前對象的屬性改變(由鍵盤或鼠標觸發)且對象失去焦點
3、onpropertychange?當前對象屬性改變就會觸發
缺陷:只支持低版本IE
4、oninput?和onpropertychange類似,當前對象屬性改變就會觸發
缺陷:不支持低版本IE
可以看出以上幾種方法都有各自的缺陷,1和2一般不能滿足需求,3和4的缺陷正好互補,兩個事件結合起來使用可以兼容IE、firefox、chrome;
所以同時綁定onpropertychange 和?oninput 可以達到實時檢測輸入內容的目的
(jquery用propertychange?和?input)。
代碼實例(jquery):
<!--superGG1990原創發表于博客園http://www.cnblogs.com/superGG1990,其他商業網站轉載均為盜版,個人博客網站轉載請注明出處 2017-05-12--> <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>監聽輸入事件</title><script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><style>b {color:red; font-size:18px;}</style> </head> <body><textarea style="width:800px; height:300px;"></textarea><div>你已經輸入了<b>0</b>個字</div><script>$('textarea').on('input propertychange',function(){var val = $(this).val()var textNum = val.length;if(textNum > 200){textNum = 200;}$('b').html(textNum)//超過200個字提示if(val.length>200){var textVal = val.substring(0,200)$(this).val(textVal)alert('評論內容大于200字')}})</script> </body> </html>
原文出處 superGG1990 ?www.cnblogs.com/superGG1990