<div class="labelRight"> <input onkeyup="WST.checkLength(this,'size01',15,1)" class="labelRight_tzName" type="text" name="tzName" value="{$obj['suitName']}"> <input type="hidden" name="suitId" id="suitId" value="{$obj['suitId']}"> <p>还能输入<span id="size01">15</span> 字</p> </div>
js部分:
WST.computeLength = function (eleInput, maxLength, nativeCharSize) { var nativeCharRegexp = /[\u4E00-\u9FFF]/; var string, char, length = 0; var ele = (typeof eleInput == 'string') ? document.getElementById(eleInput) : eleInput; if(maxLength == undefined) { maxLength = ele.maxLength || 100; } if(nativeCharSize == undefined) { nativeCharSize = 2; } string = (ele.value || '').split(''); for(var i = 0, count = string.length; i < count; i ++) { char = string[i]; if(nativeCharRegexp.test(char)) { length += nativeCharSize; } else { length ++; } } return length; } WST.checkLength = function (target,id,maxLength,zhiJie) { var maxLength = maxLength || 120; // 这是允许输入的最大数 var zhiJie = zhiJie || 1; //这是区分字节的 例如汉字是2字节 var targetLength = WST.computeLength(target, maxLength, zhiJie); // 这个是已输入的字符 var leftLength =maxLength - targetLength; if(leftLength<=0){ var val = $(target).val().slice(0,maxLength); $(target).val(val); document.getElementById(id).innerHTML = 0; $(target).keypress(function(event){ var event = event || window.event; return false; }); }else{ document.getElementById(id).innerHTML = leftLength; // 这里的size就是需要变换数字地方的Id } }