具体的思路是,获得用户输入信息的容器对象,并且在该对象的onkeydown和onkeyup事件中调用相关函数,来计算用户还可以输入多少字节。
<script language="javascript">
//定义临时变量,来存储对象的值
var mem=0;
//将中文字符的长度转换为英文字符的长度
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
//计算字符串整体长度
function Desp_value_count(obj)
{
var temp = document.getElementById(obj);
var strValue=temp.value;
//去除左空格和右空格
strValue=strValue.replace(/\r/g," ");
strValue=strValue.replace(/\n/g," ");
return utf16to8(strValue).length;
}
//把对象的值暂存在一个变量中,以便执行完utf16to8函数后,把改过的对象值还原成原来的值
function substr_desp(obj)
{
if(mem==0)
{
var test=document.getElementById(obj);
mem=test.value.length;
}
}
//带输入字符长度限制的 多加入变量 num
function LimitDesp_inputN(obj,span_obj,msg1,msg2,msg3,num)
{
var test=document.getElementById(obj);
var test_show=document.getElementById(span_obj);
if(test)
{
var input_num=parseInt(num);
test_show.className="span_match_class";
if(test.value.length==0)
{
Desp_Char_Num=(input_num+1)-Desp_value_count(obj);
mem=0;
}
if(Desp_value_count(obj)==input_num)
{
substr_desp(obj);
test_show.innerHTML=msg2+" "+0+" "+msg3;
//test.value=test.value.substr(0,mem);
return false;
}
else if(Desp_value_count(obj)>(input_num))
{
substr_desp(obj);
test_show.innerHTML=msg1;
//test.value=test.value.substr(0,mem);
return false;
}
else
{
Desp_Char_Num=(input_num+1)-Desp_value_count(obj);
Desp_Char_Num--;
test_show.innerHTML=msg2+" "+Desp_Char_Num+" "+msg3;
mem=0;
}
setTimeout(" LimitDesp_inputN()",1000);
}
}
</script>
HTML调用代码如下:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" align="right">用户信息表:</td>
<td width="71%" align="left"><input
name="szTableName"
type="text"
id="szTableName"
class="input"
maxlength="31" size="45"
οnkeydοwn="LimitDesp_inputN('szTableName','span_SzTableName','您所输入的内容超过长度限制','您还可以输入','个字符',31)"
οnkeyup="LimitDesp_inputN('szTableName','span_SzTableName','您所输入的内容超过长度限制','您还可以输入','个字符',31)" />
<span id="span_SzTableName"></span></td></tr>
</table>
实时的监控用户输入多少字节的信息
最新推荐文章于 2022-02-25 20:00:37 发布