jQuery限制TextArea里输入字符个数详解编程语言

jQuery.fn.maxLength = function(max){  
    return this.each(function(){ 
        var type = this.tagName.toLowerCase();  
        var inputType = this.type? this.type.toLowerCase() : null;  
        if(type == "input" && inputType == "text" || inputType == "password"){  
            //Apply the standard maxLength  
           // http://www.sharejs.com 
            this.maxLength = max;  
        } else if(type == "textarea"){ 
            this.onkeypress = function(e){  
                var ob = e || event;  
                var keyCode = ob.keyCode;  
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 :this.selectionStart != this.selectionEnd;  
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) &&!ob.ctrlKey && !ob.altKey && !hasSelection);  
            };  
            this.onkeyup = function(){  
                if(this.value.length > max){  
                    this.value = this.value.substring(0,max);  
                }  
            }; 
        } 
    }); 
}; 
  
//用法 www.open-open.com/code 
$('#mytextarea').maxLength(500); 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/8748.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论