功能:
1.能够实时判断输入的字节数
2.能够自动裁减超过最大长度后的内容
3.对粘贴进来的内容一样有效
4.对用鼠标拖曳进来的内容也一样有效
5.正则表达式的应用和程序的构想
源码:
<script>
function checklen(obj){
var lenE = obj.value.length;
var lenC = 0;
var CJK = obj.value.match(/[\u4E00-\u9FA5\uF900-\uFA2D]/g);
if (CJK != null) lenC += CJK.length;
tno.innerText = obj.maxlength - lenC - lenE ;
if (tno.innerText < 0) {
var tmp = 0
var cut = obj.value.substring(0, obj.maxlength);
for (var i=0; i<cut.length; i++){
tmp += /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(cut.charAt(i)) ? 2 : 1;
if (tmp > obj.maxlength) break;
}
obj.value = cut.substring(0, i);
}
}
</script>
<body onload="tno.innerText = s1.maxlength;">
<textarea name="s1" rows="5" cols="50" maxlength="1000" onpropertychange="checklen(this)"></textarea>
剩余<span id="tno"></span>个字符