Skip to content

Instantly share code, notes, and snippets.

@ifyour
Last active June 12, 2017 03:30
Show Gist options
  • Save ifyour/4ee5b9704146b848c0b8f4cbc66a9b93 to your computer and use it in GitHub Desktop.
Save ifyour/4ee5b9704146b848c0b8f4cbc66a9b93 to your computer and use it in GitHub Desktop.
基于 jQuery 的设置输入框长度的小插件, 用法: $('.input').maxLength(100,function(num,value){}); // num 剩余字数, value 变化的内容
// 适配 AMD 和 CMD 的模块化规范
;(function(factory){
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) { // 函数自执行, 当做形参
$.fn.maxLength = function(max,callback){
// this 指向原生 DOM 对象
this.each(function(){ // each 方法为每一个匹配的 DOM 元素执行一次该方法
var type = this.tagName.toLowerCase();
var inputType = this.type ? this.type.toLowerCase() : null; // 获取该 DOM 元素的属性 `type`
if(type == "input" && inputType == "text" || inputType == "password"){
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 !($.trim(this.value).length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
};
}
$(this).on('keyup change propertychange oninput',function(){
var len = $.trim(this.value).length;
if(len > max){
this.value = $.trim(this.value).substring(0,max);
return;
}
typeof callback === 'function' && callback.call(this,(max-len),this.value);
});
});
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment