js控制还能输入多少个字符

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>还可以输入多少个字符</title>
<script type="text/javascript">
    window.onload = function() {
        var oTta = document.getElementById("tta"),
            oAllNumInp = document.getElementById("all-num-inp"),
            oNeedNumInp = document.getElementById("need-num-inp"),
            oHasNumInp = document.getElementById("has-num-inp");
        
        var maxNum = 20;
        
        var oTtaVal = "";
        
        oTta.onkeyup = function() {
            checkFont();
        };
        
        oTta.onkeydown = function() {
            checkFont();
        };
        
        function checkFont() {
            oTtaVal = oTta.value;
            if(oTtaVal.length > maxNum) {
                oTta.value = oTtaVal.substring(0, maxNum);
                oNeedNumInp.value = 0;
                oHasNumInp = maxNum;    
            } else {
                oNeedNumInp.value = maxNum - oTtaVal.length;
                oHasNumInp.value = oTtaVal.length;    
            }    
        }
        
    };
</script>
</head>

<body>
    <textarea id="tta" cols="40" rows="10"></textarea>
    <div>
        <p id="all-num">一共有多少个字符:</p><input id="all-num-inp" type="text" />
    </div>
    <div>
        <p id="need-num">还可以输入</p><input id="need-num-inp" type="text" />
    </div>
    <div>
        <p id="has-num">已输入:</p><input id="has-num-inp" type="text" />
    </div>
</body>
</html>

还有一种判断的方式是:

它允许你一直输入,但是超过的时候会提示你已超出多少多少,这个思路也不错

原文地址:https://www.cnblogs.com/king-bj/p/4487956.html