日期:2014-05-16  浏览次数:20323 次

JavaScript实现textarea的maxlength
这个脚本模拟实现textarea的maxlength,无闪限制输入固定长度的字符串
目前只支持IE(ff,chrome中textarea的maxlength效果与input中的maxlength一样)
在之后会想办法做到兼容长用的浏览器


JavaScript脚本如下:
/*--------------------------------------------------|
| 文件中的对象名 | 文件路径                                                                                                                  |
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landr                |
| Email  : ianylb@sina.com、yelb@surekam.com         |
|                                                   |
| This script can be used freely as long as all     |
| copyright messages are intact.                    |
| Updated: 11.06.2011                               |
| Description: 因为textarea中没有maxlength这个属性,                           |
|           这个脚本模拟了input中maxlength功能,限定                                  |
| 输入固定长度的字符串。此脚本暂时只支持IE               |
|--------------------------------------------------*/
var MaxLengthCheck = function(){
    /**
     * 如果textarea没有maxlength属性,那么默认可输入2048个字符
     */
    var textMaxLength = 2048;
    /**
     * 当按键按下时,可绑定这个方法
     */
    this.doKeyPress = function(element, event){
        var maxLength = element.getAttribute("maxLength");
        maxLength = maxLength || textMaxLength;
        if (maxLength !== "") {
            if (element.value.length >= maxLength) {
                if (window.event) {
                    window.event.returnValue = null;
                }