看看效果:
- 可输入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