最近整理了一下jQuery扩展方法,如下
(function($) {
// 1. 滚动条滚动动画
$.fn.scrollTo = function(options) {
options = $.extend({
scrollLeft: 0,
scrollTop: 0,
speed: 200 //unit:ms
}, options);
this.stop()
.animate({ scrollLeft: options.scrollLeft, scrollTop: options.scrollTop }, options.speed);
return this;
};
// 2. 设置 div 在屏幕中央
$.fn.center = function() {
var $win = $(window);
this.css({
'position': 'absolute',
'top': ($win.height() - this.height()) / 2 + $win.scrollTop() / 2,
'left': ($win.width() - this.width()) / 2 + $win.scrollLeft() / 2
});
return this;
};
// 3. 检测鼠标的右键和左键
$('body').mousedown(function(e) {
alert(e.which); // 1: 鼠标左键 2:鼠标中键 3:鼠标右键
});
// 4. 回车提交表单
$(':text, :password').keyup(function(e) {
if (e.which == "13") {
alert('回车提交');
}
});
// 5. 扩展 String 对象的方法
$.extend(String.prototype, {
isPositiveInteger: function() {
return /^[1-9]+\d*$/.test(this);
},
isInteger: function() {
return /^\d+$/.test(this);
},
isNumber: function() {
return /^-?([0-9]*)(\.[0-9]+)?$/.test(this);
},
ltrim: function() {
return this.replace(/^\s+/, '');
},
rtrim: function() {
return this.replace(/\s+$/, '');
},
trim: function() {
return this.replace(/(^\s+*)|(*\s+$)|\r|\n/g, '');
}
});
// 6.数字转成千分位字符串
// 注意:使用时,不能直接 123.toCurrencyString(),应该先定义变量,如:var num = 123; num.toCurrencyString();
$.extend(Number.prototype, {
toCurrencyString: function() {
// 匹配每一个数字,找到右边含有三个小数点且有3个倍数个数字的数字,将其替换为本身加逗号
return this.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}
});
// 7. 输入框/下拉框/单选按钮/checkbox只读/取消只读
$.fn.Lockdown = function(lock) {
var lock = typeof(lock) == "undefined" ? true : lock;
if (this.is('select')) {
// 对于select,使用时,外面需要嵌套一个block的元素
if (lock) {
if (this.prev('[name=mask_layer]').length == 0) {
var scrollTop = $('body').scrollTop();
var scrollLeft = $('body').scrollLeft();
this.css('color', '#666');
this.before('<div name="mask_layer" style="width:' + (this.width() + 4) + 'px;height:' +
(this.height() + 2) +
'px;background-color:#666;opacity:.10;position:absolute;"></div>');
}
} else {
this.css('color', 'black');
this.parent().find('div[name=mask_layer]').remove();
}
} else if (this.is(':radio') || this.is(':checkbox')) {
var n = this.attr('name');
var v = $('[name=' + n + ']:checked').val();
var es = $('[name=' + n + ']').not(':hidden');
$('input[name=' + n + '][type=hidden]').remove(); //remove old hidden input
if (lock && typeof(v) != 'undefined') {
debugger
var c = $('<input type="hidden" />')
c.attr('name', n)
c.val(v);
this.parent().append(c);
}
es.each(function() {
$(this).prop('disabled', true);
});
} else {
if (lock) {
$(this).attr("readonly", true);
} else {
$(this).attr("readonly", false);
}
}
};
// 8. 移除输入的数字开头的0
$.extend({
removeZeroInStartForMoneyFilter: function() {
$("div[filter*=MONEY] > input").blur(function() {
// 传入,则如果开头出现0,则弹出错误信息;否则,直接移除开头的0
var moneyCheck = $(this).attr('moneycheck');
// 输入的数字是否可以等于0,如果可以为0,则多个0时只保留1个0
var canBeZero = $(this).attr('canbezero');
var $cur = $(this);
var val = $cur.val();
var msg = $cur.parent().find('span').text();
if (typeof(canBeZero) != 'undefined' && val.replace(/,/g, '').search(/^(\$)?0+(\.[0]+)?$/) == 0) {
// value can be zero and is zero, just reserve one zero
$cur.val('$0');
} else if (typeof(moneyCheck) == 'undefined') {
// If without moneycheck attribute, just remove zero in start
var tmp = val.replace(/^([$])?(0(,)?)+(?![.])/, '');
tmp = tmp[0] == '$' ? tmp : '$' + tmp;
$(this).val(tmp);
} else if (val.replace(/,/g, '').search(/^(\$)?0+(\.[0]+)?$/) == 0) {
// If can not be zero and is zero and money check needed, alert prompt
alert(msg + ' must be greater than 0.');
} else {
// If with moneycheck attribute, don't remove zero in start, just alter prompt
if (val != '' && val.search(/^(\$)?(0)+(?!\.)/) == 0) {
alert(moneyCheck + ' cannot begin with a zero.');
}
}
}).focus(function() {
var moneyCheck = $(this).attr('moneycheck');
if (typeof(moneyCheck) == 'undefined') {
// 获取焦点时移除开头的0
$(this).val($(this).val().replace(/^(0)+(?![.])/, ''));
}
});
}
});
// 9. 日期格式化
Date.prototype.pattern = function dateFormat(fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
var week = {
"0": "/u65e5",
"1": "/u4e00",
"2": "/u4e8c",
"3": "/u4e09",
"4": "/u56db",
"5": "/u4e94",
"6": "/u516d"
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
})(jQuery);