js 限制文本框输入字数

原文链接: http://www.cnblogs.com/aizhan/archive/2013/01/22/IceBirds.html

可主要用于留言板等地的小部分文字书写。

代码如下:

   <head id="Head1" runat="server">

    <title>限制文本框输入字数</title>

    <style type="text/css">

        .progress

        {

            width: 1px;

            height: 14px;

            color: white;

            font-size: 12px;

            overflow: hidden;

            background-color: navy;

            padding-left: 5px;

        }

    </style>

 

    <script type="text/JavaScript">

function textCounter(field,counter,maxlimit,linecounter) {

 // text width//

 var fieldWidth =  parseInt(field.offsetWidth);

 var charcnt = field.value.length;       

 // trim the extra text

 if (charcnt > maxlimit) {

  field.value = field.value.substring(0, maxlimit);

 }

 else {

 // progress bar percentage

 var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;

 document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";

 document.getElementById(counter).innerHTML="已输: "+percentage+"%"

 // color correction on style from CCFFF -> CC0000

 setcolor(document.getElementById(counter),percentage,"background-color");

 }

}

function setcolor(obj,percentage,prop){

 obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";

}

    </script>

 

    <p>

        限制:120字节</p>

</head>

<body>

    <form id="form1" runat="server">

    <textarea rows="5" cols="40" name="maxcharfield" id="maxcharfield" onkeydown="textCounter(this,'progressbar1',120)"

        onkeyup="textCounter(this,'progressbar1',120)" onpaste="textCounter(this,'progressbar1',120)"

        onfocus="textCounter(this,'progressbar1',120)"></textarea><br />

    <div id="progressbar1" class="progress">

    </div>

 

    <script type="text/jscript">textCounter(document.getElementById("maxcharfield"),"progressbar1",120)</script>

    </form>

</body>

以前用的,感觉不错……

转载于:https://www.cnblogs.com/aizhan/archive/2013/01/22/IceBirds.html

猜你喜欢

转载自blog.csdn.net/weixin_30596023/article/details/94856539