<html>
<body>
<textarea id="t"></textarea>
<input type="text" id="b2" />
<script type="text/
javascript">
textAreaLimit("t",{lastMsgLabel:"b2"})
function textAreaLimit(area,op){
var defaultOp = {
maxLength:10 //最大长度
, IsNumber:false //只能是数字
, lastMsgLabel:null //即时显示可输入个数的Input
, msg:"还可以输入{0}个文字"
, errorMsg:"文字个数超出最大限制"
};
var label;
if(typeof area == "string"){
area = document.getElementById(area);
}
if(!area){
return;
}
for(var i in op){
defaultOp[i] = op[i];
}
if(defaultOp.lastMsgLabel){
if(typeof defaultOp.lastMsgLabel == "string"){
label = document.getElementById(defaultOp.lastMsgLabel);
}
}
if(defaultOp.IsNumber){
area.style.imeMode="
disabled";//IE
area.onkeydown = function(){
return event.keyCode != 229;
}
}
area.onkeyup = function(){
if(defaultOp.IsNumber){
this.value = this.value.replace(/D/g,"");//IE之外的
}
if(this.value.length > defaultOp.maxLength){
//-------------------------------------------------------------------------------
//方案①
this.disabled = "disabled";
this.value = this.value.slice(0,defaultOp.maxLength);
this.removeAttribute("disabled");
this.focus();
//方案②
//或
//alert(defaultOp.errorMsg);
//this.value = this.value.slice(0,defaultOp.maxLength);
//-------------------------------------------------------------------------------
}
if(label){
label.value = defaultOp.msg.replace(/{0}/,defaultOp.maxLength -this.value.length);
}
}
}
</script>
</body>
</html>