JS 限制input框的输入字数,并提示可输入字数

时间:2021-12-03 11:54:33
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>限制文件字数字</title>
</head>
<body>
<span class="span">备注信息</br><span id="stay" style="display: none"> 您还可以输入:<span id="txtCount"></span>个字符的描述信息</span></span>
         </br><input id="Remark_information" name="Remark_information" type="text">

         <script>
    var lim=new limit();
    lim.txtNote=document.getElementById("Remark_information");
    lim.txtLimit=document.getElementById("txtCount");
    lim.limitCount=80;
    lim.init();
    function limit(){
        var txtNote;//文本框
        var txtLimit;//提示字数的input
        var limitCount;//限制的字数
        var txtlength;//到达限制时,字符串的长度
        this.init=function(){
            txtNote=this.txtNote;
            txtLimit=this.txtLimit;
            limitCount=this.limitCount;
            txtNote.oninput=function(){wordsLimit()};txtNote.oninput=function(){wordsLimit()};
            txtLimit.innerText=limitCount;
        };
        function wordsLimit(){
            var noteCount=txtNote.value.length;
            var InPut=document.getElementById("Remark_information").value.length;
            if(InPut<1){
                document.getElementById("stay").style.display="none";
                return
            }
            if(InPut>=1){
                document.getElementById("stay").style.display="inline";
                document.getElementById("stay").style.color="green";
            }
            if(InPut>70){
                document.getElementById("stay").style.color="red";
            }
            if(noteCount>limitCount){
                txtNote.value=txtNote.value.substring(0,limitCount);
                txtLimit.innerText=0;
            }else{
                txtLimit.innerText=limitCount-noteCount;
            }
            txtlength=txtNote.value.length;//记录每次输入后的长度
        }
    }
</script>
</body>

来自:http://www.cnblogs.com/zhujiasheng/p/6113983.html