html代码:
<div class="news-edit">
<label for="" class="edit-titlelabel">标题</label>
<span class="news-inputbox"><input type="text" placeholder="请输入文本" id="title" onkeydown="check_input('title','remLen',36);" onkeyup="check_input('title','remLen',36);"/></span>
<span class="wordnum-limit"><span id="remLen">0/18</span></span>
</div>
js代码:
//该函数用于输出框,当输入值大于指定的最大值的时候,返回当长度等于Max的值
function getByteVal(val, max) {
var returnValue = '';
var byteValLen = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].match(/[^x00-xff]/ig) != null)
byteValLen += 2;
else
byteValLen += 1;
if (byteValLen > max)
break;
returnValue += val[i];
}
return returnValue;
}
//该函数用户计算输入框中 的输入值的长度,其中中文为2,英文为1,数字为1
function countCharacters(str){
var totalCount = 0;
//alert("ss");
for(var i=0; i<str.length; i++){
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)){
totalCount++;
}else{
totalCount+=2;
}
}
return totalCount;
}
//该函数用于检验输入值,在该函数中调用了以上两个函数
function check_input(id,remId,max){
var send_wb_count=max;
//var txt = id.value;
var txt=document.getElementById(id).value;
//alert(txt);
var wb_count = countCharacters(txt);
//var info=id.next();
if(wb_count > send_wb_count){
//$('#send_weibo').val(txt.substring(0,130));
//id.val(getByteVal(txt,max));
$("#"+id).val(getByteVal(txt,max));
//alert(id.val(getByteVal(txt,max)));
$("#"+remId).html("长度超过"+send_wb_count/2) ;
}else{
$("#"+remId).html(Math.floor((send_wb_count-wb_count)/2)+"/"+max/2) ;
}
}