控制texterea长度,并显示剩余字数,只能在IE上运行
<script>
function checklen(obj){
var lenE = obj.value.length;
var lenC = 0;
var CJK = obj.value.match(/[u4E00-u9FA5uF900-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-u9FA5uF900-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="100" onpropertychange="checklen(this)"></textarea>
剩余<span id="tno"></span>个字符
附:Javascript中的trim和replace函数===============
//triml();
triml = function () {
for (var i = 0; i < this.length; i++) {
if (this.charcodeat (i) > 32) {
return this.substr (i, this.length);
}
}
return this;
}
//trimr();
trimr = function () {
for (var i = this.length; i > 0; i--) {
if (this.charcodeat (i) > 32) {
return this.substring (0, i + 1);
}
}
return this;
}
//trimwhite();
trimwhite = function() {
this = this.triml ();
return this.trimr ();
}
//replace();
function replace():string {
var str:string = string(arguments[0]);
var re_str:string = string(arguments[1]);
var new_str:string = string(arguments[2]);
if (arguments.length<3||re_str=="") {
return str;
}
while (str.indexof(re_str) != -1 && str != "") {
str_b = str.indexof(re_str);
str_e = str_b+re_str.length-1;
if (str_b != 0 && str_e != str.length-1) {
str = str.substr(0, str_b)+new_str+str.substr(str_e+1, str.length-1);
} else if (str_b == 0) {
str = new_str+str.substr(str_e+1, str.length-1);
} else {
str = str.substr(0, str_b)+new_str;
}
}
return str;
}