版权声明:本文为CSDN博主「weixin_43431702」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43431702/article/details/89191644
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
input{
display: block;
width: 100%;
}
</style>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
// 这是第一种最寻常的方法
//定义一个函数
function checkField(value, byteLength, attribute) {
// value是input框的值,byteLength是需求限制的字符,attribute是input的id名
const newvalue = value.replace(/[^\x00-\xff]/g, "**");
const length = newvalue.length;
//当填写的字节数小于设置的字节数
if (length <= byteLength * 1) {
return;
}
const limitDate = newvalue.substr(0, byteLength);
let count = 0;
let limitValue = "";
for (let i = 0; i < limitDate.length; i++) {
const flat = limitDate.substr(i, 1);
if (flat === "*") {
count++;
}
}
let size = 0;
let istar = newvalue.substr(byteLength * 1 - 1, 1); //校验点是否为“×”
//if 基点是×; 判断在基点内有×为偶数还是奇数
if (count % 2 === 0) {
//当为偶数时
size = count / 2 + (byteLength * 1 - count);
limitValue = value.substr(0, size);
} else {
//当为奇数时
size = (count - 1) / 2 + (byteLength * 1 - count);
limitValue = value.substr(0, size);
}
alert(
"最大输入" +
byteLength +
"个字节(相当于" +
byteLength / 2 +
"个汉字)!"
);
document.getElementById(attribute).value = limitValue;
}
</script>
</head>
<body>
<div class="wrap">
<form>
<table class="list-style">
<tr>
<td>
<input id="profession" type="text" oninput="checkField(this.value,20,'profession')" class="textBox length-middle" name="profession"/>
<input id="interest" type="text" oninput="checkField(this.value,10,'interest')" class="textBox length-middle" name="interest"/>
<input id="address" oninput="checkField(this.value,40,'address')" type="text" class="textBox length-middle" name="address" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>