JS TextArea字串長度限制代碼集合

來源:互聯網
上載者:User

複製代碼 代碼如下:
<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>

解決輸入日語+全形時出現的BUG 主要是在紅線中間的代碼。
思路就是中斷日語的輸入狀態。
用如果輸入超出時能忍受彈窗的話,就用方案②,否則的話就用方案①。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.