功能/特點:
1.即時顯示可輸入的字數(位元組數)
2.兩種限制方式(長度、位元組數)
3.中文IME下可正常使用,無BUG
4.同一頁面可以使用多個,相互不干擾
limit.js
function limit(){<br />var txtNote;//文字框<br />var txtLimit;//提示字數的input<br />var limitCount;//限制的字數<br />var isbyte;//是否使用位元組長度限制(1漢字=2字元)<br />var txtlength;//到達限制時,字串的長度<br />var txtByte;<br />this.init=function(){<br />txtNote=this.txtNote;<br />txtLimit=this.txtLimit;<br />limitCount=this.limitCount;<br />isbyte=this.isbyte;<br />txtNote.onkeydown=function(){wordsLimit()};txtNote.onkeyup=function(){wordsLimit()};<br />txtLimit.value=limitCount;<br />}<br />function wordsLimit(){<br />var noteCount=0;<br />if(isbyte){noteCount=txtNote.value.replace(/[^/x00-/xff]/g,"xx").length}else{noteCount=txtNote.value.length}<br />if(noteCount>limitCount){<br />if(isbyte){<br />txtNote.value=txtNote.value.substring(0,txtlength+Math.floor((limitCount-txtByte)/2));<br />txtByte=txtNote.value.replace(/[^/x00-/xff]/g,"xx").length;<br />txtLimit.value=limitCount-txtByte;<br />}else{<br />txtNote.value=txtNote.value.substring(0,limitCount);<br />txtLimit.value=0;<br />}<br />}else{<br />txtLimit.value=limitCount-noteCount;<br />}<br />txtlength=txtNote.value.length;//記錄每次輸入後的長度<br />txtByte=txtNote.value.replace(/[^/x00-/xff]/g,"xx").length;<br />}<br />}
頁面調用:
<html><br /><body><br /><input id="txtNote" /><br />還可輸入<input type="text" id="txtCount" />個字元<br /></body><br /><mce:script type="text/javascript"><!--<br />var lim=new limit();<br />lim.txtNote=document.getElementById("txtNote");<br />lim.txtLimit=document.getElementById("txtCount");<br />lim.limitCount=20;<br />lim.isbyte=true;<br />lim.init();<br />// --></mce:script><br /></html>