文本域限制字数并且超多的字数自动替换成空:
<textarea cols='30' rows=2 onkeyup=checkTextArea(this,60) onkeydown =checkTextArea(this,60) style="overflow:hidden;"></textarea> <p> 还可以输入:<em id='limittip'>60</em>字 </p>
<script type="text/javascript"> function checkTextArea(obj,maxWords){ var limit = maxWords; var limittip = document.getElementById('limittip'); var str = obj.value; var len = str.length; var reallen = 0; for(i=0;i<len;i++){ if(str.charCodeAt(i)>255){ reallen += 2; if(reallen > limit){ reallen -= 2; obj.value = str.substr(0,i); break; } } else{ reallen++; if(reallen > limit){ reallen--; obj.value = str.substr(0,i); break; } } } limittip.innerHTML = limit - reallen; } </script>
原文参考地址:http://www.decimage.com/web/js-for-textarea-count-bytes.html