效果如图;解决输入时拼音长度也算字符串长度的问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
还可以输入<span id="word">10</span>个字<br />
<textarea id="txt" maxlength="10"></textarea>
</body>
</html>
<script language="javascript" type="text/javascript">
var txt = document.getElementById("txt");
var txtNum = document.getElementById("word");
var maxlength = 10;
var sw = false; //定义关闭的开关
txt.addEventListener("keyup", function () {
if (sw == false) {
countTxt();
}
});
//ompositionstart在输入中文或者语音等需要等待一连串的输入的操作之前触发
txt.addEventListener("compositionstart", function () {
sw = true;
});
//compositionend在输入中文或者语音等完毕或取消时触发
txt.addEventListener("compositionend", function () {
sw = false;
countTxt();
});
//这两个属性有点类似于“开关”,如:开始输入拼音时开关打开,不再改变监测得到的长度数值。用拼音完整输入一个或是一串文字后,开关关闭,此时得到监测的数值长度。
function countTxt() { //计数函数
if (sw == false) { //只有开关关闭时,才赋值
txtNum.textContent = maxlength - txt.value.length;
}
}
</script>