看看效果:
- 可輸入5個位元組:
- 可輸入6個位元組:
- 可輸入7個位元組:
- 可輸入n個位元組:
代碼如下:(本來基于原型封裝了一下,發現完全在增加代碼量,又改回來了)
感謝sparks345提出粘貼時的問題
這樣的話,隻能多加幾個事件onpropertychange,oninput, obj.watch("value",function(id,oval,nval){})
具體可以看這裡,跟蹤input值改變相容處理
code here <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > 限制輸入位元組數 </ title >
< meta name ="author" content ="sohighthesky" />
< style type ="text/css" >
#div1 { width : 500px ; margin : 20px auto ; }
#div1 ul { list-style-type : decimal ; line-height : 25px ; }
</ style >
</ head >
< body >
< div id ="div1" >
< ul >
< li > 可輸入5個位元組: < input type ="text" id ="txt1" value ="你好e" /></ li >
< li > 可輸入6個位元組: < input type ="text" id ="txt2" value ="hello," /></ li >
< li > 可輸入7個位元組: < input type ="text" id ="txt3" value =",he" /></ li >
< li > 可輸入n個位元組: < input type ="text" id ="txt4" /></ li >
</ ul >
</ div >
</ body >
< script type ="text/javascript" >
! function (){
var len = function (s){ // 擷取字元串的位元組長度
s = String(s);
return s.length + (s.match( / [^\x00-\xff] / g) || "" ).length; // 加上比對到的全角字元長度
},
limitDo = function (limit){
var val = this .value;
if (len(val) > limit) {
// val=val.substr(0,limit);
while (len(val = val.substr( 0 ,val.length - 1 )) > limit);
this .value = val;
}
},$ = function (id){ return typeof (id) === ' string ' ? document.getElementById(id):id;};
$( " txt1 " ).onkeyup = function (){limitDo.call( this , 5 )};
$( " txt2 " ).onkeyup = function (){limitDo.call( this , 6 )};
$( " txt3 " ).onkeyup = function (){limitDo.call( this , 7 )};
}();
</ script >
</ html >
轉載于:https://www.cnblogs.com/sohighthesky/archive/2010/01/16/input-maxsize-limit.html