一个简单的javascript字符计数器

By | March 10, 2009

公司一个项目里有发短信功能,要在页面上提示用户还剩多少字符可以输入,当用户输入的字符数超过最大字符限制,则截取最大字符数的数目。代码还是比较简单的,也算是记录一下。
代码如下:
HTML部分:

<textarea id="txtContainer" rows="3" cols="40" ></textarea>
<br />
words left: <input id="txtWordCount" type="text" readonly="true" style="width:40px;" />

javascript部分:

<script type="text/javascript">

    function containerKeyupHandler( e ){
        var count = "10";

        var evt = e || window.event;
        var elm = evt.target || evt.srcElement;

        var tex = elm.value;
        var len = tex.length;
        var wordCount = document.getElementById("txtWordCount");
        wordCount.value = count - len;
        if(len > count){
                tex = tex.substring(0,count);
                elm.value =tex;
                wordCount.value = 0;
                return false;
        }
    }

    function addEvent(elm, evType, fn, useCapture) {
        if (elm.addEventListener) {
            elm.addEventListener(evType, fn, useCapture);
            return true;
        }
        else if (elm.attachEvent) {
            var r = elm.attachEvent('on' + evType, fn);
            return r;
        }
        else {
            elm['on' + evType] = fn;
        }
    }

    addEvent( document.getElementById("txtContainer"), "keyup", containerKeyupHandler );
</script>  

显示效果:

image

代码下载:

点击下载