限制字数(半角全角)

来源:互联网 发布:农村淘宝合伙人可以吗 编辑:程序博客网 时间:2024/05/19 17:10
<script type="text/javascript"> function checkLength() { var which = $("#content").val();var totalLength = 0;var maxChars = 140; var list = which.split("");//if (list.length > maxChars) //list.value = list.value.substring(0,maxChars); for(var i = 0; i < list.length; i++) {var s = list[i];   if (s.match(/[\u0000-\u00ff]/g)) { //半角    totalLength += 0.5;   } else if (s.match(/[\u4e00-\u9fa5]/g)) { //中文     totalLength += 1;   } else if (s.match(/[\uff00-\uffff]/g)) { //全角    totalLength +=1;   }  }  var curr = maxChars - totalLength; if(curr >= 0){    $("#shuru").show();    $("#chaochu").hide();    $("#content_chaochu").val(1);//在限制范围内为1    document.getElementById("chLeft").innerHTML = parseInt(curr.toString()); }else{    var chao = totalLength - maxChars;    if(chao > 0){        $("#chLeft_chao").css('color','#FF0000');        $("#shuru").hide();        $("#chaochu").show();        $("#content_chaochu").val(2);//超出范围内为2        document.getElementById("chLeft_chao").innerHTML = parseInt(chao.toString());    } }return false;} </script><p class="clearfix">            <span class="fr" id="shuru">还可以输入<span class="w-fs" id="chLeft">140</span>字</span><span class="weibo-tit"></span>            <span class="fr" id="chaochu" style="display:none">已经超出<span class="w-fs" id="chLeft_chao">140</span>字</span><span class="weibo-tit"></span></p><textarea name="content" id="content" class="weibo-area" onkeyup="checkLength()"></textarea><input type="hidden" id="content_chaochu" value="1" />
0 0