JS限制文字框錄入長度(支援字元限制)

來源:互聯網
上載者:User

 功能/特點:

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>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.