;(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery', 'handlebars'], factory);
} else {
factory(jQuery);
}
})(function($, handlebars) {
$.extend({
// 验证手机号是否正确
checkTel: function(tel) {
if(!(/^1[3|4|5|7|8]\d{9}$/.test(tel))) {
return false;
} else {
return true;
}
},
// 验证网址是否正确
checkUrl: function(url) {
if(!(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(url))){
return false;
}else{
return true;
}
},
// 手机页面的信息提示
msg: function(txt) {
if($("#fdvuir7rw4d").length != 0) {
$("#fdvuir7rw4d").remove();
}
var html = '';
html += '
';
html += '';
html += txt;
html += '';
html += '
';
$("body").append(html);
setTimeout(function() {
$("#fdvuir7rw4d").fadeOut(800,function() {
$(this).remove();
});
}, 400);
},
alert: function(message, func) {
var message = message || '网络繁忙,请稍后再试';
var $dom = $('\
\
\
'+ message +'
\
\
确定\
\
\
');
$('.alertModal').length && $('.alertModal').remove();
$dom.appendTo($('body'));
$dom.on('click', 'a.done, a.close', function() {
$dom.remove();
$(document).off('keyup.alert');
if (func && typeof func == "function") func();
})
$(document).on('keyup.alert', function(e) {
if (e.keyCode == 27 || e.keyCode == 13) {
$dom.remove();
$(document).off('keyup.alert');
if (func && typeof func == "function") func();
}
})
},
message: function(message) {
var $dom = $(''+ message +'
');
$dom.appendTo($('body'));
setTimeout(function() {
$dom.fadeOut(600, function(){
$dom.remove();
});
}, 500);
},
alertNew: function(message, showAfter,func) {
var message = message || '网络繁忙,请稍后再试';
var $dom = $('\
\
\
'+ message +'
\
\
确定\
\
\
');
$('.alertModal').length && $('.alertModal').remove();
$dom.appendTo($('body'));
if ($.isFunction(showAfter)) {
showAfter($dom);
};
$dom.on('click', 'a.done, a.close', function() {
$(document).off('keyup.alert');
if (func && typeof func == "function") {
if(func($dom)){
$dom.remove();
}
};
})
$(document).on('keyup.alert', function(e) {
if (e.keyCode == 27 || e.keyCode == 13) {
$(document).off('keyup.alert');
if (func && typeof func == "function") {
if(func($dom)){
$dom.remove();
}
};
}
})
},
confirm: function(message, done, cancel) {
var message = message || '确定要进行此操作吗?';
var $dom = $('\
\
\
'+ message +'
\
\
确定\
取消\
\
\
');
$('.alertModal').length && $('.alertModal').remove();
$dom.appendTo($('body'));
$dom.on('click', 'a.done', function() {
if (done && typeof done == "function") {
done($dom);
$(document).off('keyup.alert');
}
}).on('click', 'a.cancel', function() {
if (cancel && typeof cancel == "function") {
cancel($dom);
$(document).off('keyup.alert');
} else {
$dom.remove();
$(document).off('keyup.alert');
}
}).on('click', 'a.close', function() {
$dom.remove();
$(document).off('keyup.alert');
});
$(document).on('keyup.alert', function(e) {
$(document).off('keyup.alert');
if (e.keyCode == 27) {
$dom.remove();
}
if (e.keyCode == 13) {
$dom.find('a.done').trigger('click');
}
})
},
// 获取网址参数值
getUrlParam: function(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return r[2];
return null;
},
// 获取时间戳所在月的第一天(返回一个时间对象)
getFirstDayObj: function(timestamp) {
var date = new Date(parseInt(timestamp));
date.setDate(1);
return date;
},
// 获取时间戳所在月的最后一天(返回一个时间对象)
getLastDayObj: function(timestamp) {
var date = new Date(parseInt(timestamp)),
currentMonth = date.getMonth(),
nextMonth = ++currentMonth,
lastDate = new Date(date.getFullYear(),nextMonth,0);
return lastDate;
},
// 获取月份有多少天
getCountDays: function(timestamp) {
var curDate = new Date(timestamp),
curMonth = curDate.getMonth();
curDate.setMonth(curMonth + 1);
curDate.setDate(0);
return curDate.getDate();
},
// 管理员后台alert模版
systemAlert: function(msg, opt) {
var self = this,
html = '',
$modal = $(handlebars.compile(html)({'message': msg}));
$modal.appendTo($('body'));
$modal.fmodal(opt || {show: true});
},
// 管理员后台confirm模版
systemConfirm: function(options) {
var self = this,
defaults = {
message: '',
confirm: function($tpl){}
},
opt = $.extend({}, defaults, options),
html = '',
$modal = $(handlebars.compile(html)({'message': opt.message}));
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
if(typeof opt.confirm === 'function') opt.confirm.call(this, $modal);
}
});
},
// 管理系统等待加载
systemLoader: function(sign) {
var self = this,
html = '';
if(!sign){
var t = setTimeout(function() {
$('body').append(html);
}, 500);
return t;
}else{
clearTimeout(sign);
$('#loader').remove();
}
return false;
},
loader: function($target) {
var html = '';
if($target) {
$target.css({'position': 'relative', 'min-height': '20px'}).append(html);
}else{
$('body').append(html);
}
}
});
handlebars.registerHelper({
'diyIf': function(value, options) {
if (value) {
return options.fn(this);
} else {
return options.inverse(this);
}
},
'diyWith': function(value, arr, options) {
if ($.inArray(value, arr) > 0) {
return options.fn(this);
}
},
'diyNull': function(value, options) {
if (!value) {
return options.fn(this);
} else {
return options.inverse(this);
}
},
'diyQqual': function(v1, v2, options) {
if (v1 == v2) {
return options.fn(this);
} else {
return options.inverse(this);
}
},
//返回数组某一个索引的某一个字段的值
'arrForIndex': function(v1, index, field, options) {
if(!field){
return v1[index]
} else {
return v1[index].field
}
},
//简单加法(未做精度预算)
'simpleAdd': function(num1, num2, options) {
var sq1, sq2, m;
try {
sq1 = parseFloat(num1).toString().split(".")[1].length;
} catch (e) {
sq1 = 0;
}
try {
sq2 = parseFloat(num2).toString().split(".")[1].length;
} catch (e) {
sq2 = 0;
}
m = Math.pow(10,Math.max(sq1, sq2));
return (num1 * m + num2 * m) / m;
},
//旺旺价格计算
'wwOrderPrice': function(num1, num2, num3, options) {
var k = parseFloat(num2) / parseFloat(num3),
sq1, sq2, m;
try {
sq1 = parseFloat(num1).toString().split(".")[1].length;
} catch (e) {
sq1 = 0;
}
try {
sq2 = parseFloat(k).toString().split(".")[1].length;
} catch (e) {
sq2 = 0;
}
m = Math.pow(10,Math.max(sq1, sq2));
return (num1 * m + k * m) / m;
},
//对比大小
'greaterThan': function(v1, v2, options) {
if(v1 > v2){
return options.fn(this);
} else{
return options.inverse(this);
}
}
})
/**
* time:倒计时持续时长
* txt:倒计时中显示的文本
* classname:倒计时进行时元素应呈现的class
* callback:回调函数
* PS:先执行回调再倒计时
*/
$.fn.timer = function(options) {
var self = $(this);
if (self.data('lock')) {return;}
var time = options.time || 60,
txt = options.txt || 's后重新发送',
classname = options.classname || 'on',
callback = options.callback || function(){},
start_txt = self.text(),
time = parseInt(time);
self.text(time + txt).addClass(classname).data('lock',true);
// 执行回调函数
var fn = eval(callback);
if(typeof fn === 'function') fn.call(this);
var t = setInterval(function() {
time--;
if(time <= 0){
clearTimeout(t);
self.removeClass(classname).text(start_txt).data('lock',false);
}else{
self.text(time + txt);
}
}, 1000);
};
/**
* 过渡动画结束后执行回调函数
* callback: 回调函数
*/
$.fn.transitionEnd = function(callback) {
var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],i,dom = this;
function fireCallBack(e) {
if (e.target !== this) return;
callback.call(this, e);
for (i = 0; i < events.length; i++) {
dom.off(events[i], fireCallBack);
}
}
if (callback) {
for (i = 0; i < events.length; i++) {
dom.on(events[i], fireCallBack);
}
}
return this;
};
// 仿选择框
$.fn.fcheck = function() {
var self = this;
self.each(function() {
if($(this).data('fcheck')) return true;
var $fcheck = $(this);
var $input = $(this).find('input');
var checked = $input.prop("checked");
checked ? $(this).addClass('checked') : $(this).removeClass('checked');
$input.on('change', function() {
var checked = $(this).prop("checked");
checked ? $fcheck.addClass('checked') : $fcheck.removeClass('checked');
});
$(this).data('fcheck',true);
});
};
// 仿输入框(商家端招募客服页面可以点击增减数值的输入框)
$.fn.finput = function(options) {
var self = this,
defaults = {
change: function(){}
};
self.options = $.extend({}, defaults, options);
self.each(function() {
$(this).append('');
var $input = $(this).find('input'),
$plus = $(this).find('.plus'),
$minus = $(this).find('.minus'),
step = $(this).data('step') || 1,
max = $(this).data('max') !== undefined ? parseInt($(this).data('max')) : null,
min = $(this).data('min') !== undefined ? parseInt($(this).data('min')) : null,
startVal = $input.val(),
event = eval(self.options.change);
if (startVal == '') {
$input.val(min === null ? ((max === null || max > 0) ? 0 : max) : min);
} else {
if(min !== null && startVal < min) startVal = min;
if(max !== null && startVal > max) startVal = max;
$input.val(startVal);
}
$input.on('blur', function() {
var value = $(this).val(),
val = value.replace(/\D|^0/g,'');
if(min !== null && val < min) val = min;
if(max !== null && val > max) val = max;
$(this).val(val);
if(typeof event === 'function') event.call(this, val);
});
$plus.on('click', function() {
var val = (parseInt($input.val()/step) + 1)*step;
if(max !== null && val > max) val = max;
$input.val(val);
if(typeof event === 'function') event.call(this, val);
});
$minus.on('click', function() {
var inputVal = parseInt($input.val()),
stepLength = parseInt(inputVal / step),
val = inputVal%step ? (stepLength*step) : ((stepLength - 1)*step);
if(min !== null && val < min) val = min;
$input.val(val);
if(typeof event === 'function') event.call(this, val);
});
});
};
// 元素滚动到底部后执行回调
// 设置data('lockscroll') 判断是否要执行回调函数 (在获取数据时和已无更多数据时,不应该执行回调)
$.fn.scrollToBottom = function(callback) {
var self = $(this);
if($(this).data('bindscroll')) return;
var height = $(this).outerHeight(),
e = eval(callback),
sign = (typeof e === 'function');
self.scroll(function() {
var totalHeight = $(this)[0].scrollHeight,
scrollTop = $(this).scrollTop();
if((height + scrollTop + 10) >= totalHeight && sign) {
if(self.data('lockscroll')) return;
self.data('lockscroll', true);
e.call(this);
}
});
$(this).data('bindscroll',true);
};
// 整数输入框。str为'+'只能输入正整数,否则可输入包括0的正整数
$.fn.intInput = function(str) {
var self = this;
self.each(function() {
$(this).on('blur', function() {
var value = $(this).val(),
val = (str == '+') ? value.replace(/\D|^0/g,'') : value.replace(/\D|^/g,'');
$(this).val(val);
});
});
};
// 小数输入框。
$.fn.floatInput = function() {
var self = this;
self.each(function() {
$(this).on('blur', function() {
var value = $(this).val(),
value = value.replace(/[^\d.]/g,''),
value = value.replace(/^\./g,''),
value = value.replace(/\.{2,}/g,'.');
$(this).val(value);
});
});
};
//序列化后表单值转换成Json
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// 通过输入框输入的值动态获取数据(如百度搜索) 例:$('input').dynamicGetData({input: fn, select: fn, cancel: fn, enter: fn});
$.fn.dynamicGetData = function(options) {
var self = this,
defaults = {
input: function(){},
cancel: function(){},
select: function(){},
enter: function(){}
};
self.options = $.extend({}, defaults, options);
self.each(function() {
var $this = $(this),
formUrl = $this.data('url');
if(!formUrl) return true;
$this.wrap('');
$this.after('');
var $box = $this.closest('.ajax-input-coat'),
$list = $box.find('.list');
$list.on('click', 'li', function(){
var text = $(this).text(),
$objs = {
input: $this,
list: $list,
selected: $(this)
};
$this.val(text);
$list.hide();
if(typeof self.options.select === 'function') self.options.select.call(this, $objs);
});
$this.on('input', function(){
var val = $this.val().trim(),
oldVal = $this.data('val') || '',
$objs = {
input: $this,
list: $list
};
if(val === oldVal) return
$this.data('val',val);
if(val === ''){
$list.hide();
if(typeof self.options.cancel === 'function') self.options.cancel.call(this, $objs);
return;
}
if(typeof self.options.input === 'function') self.options.input.call(this, $objs);
}).on('keyup', function(e) {
var code = e.keyCode,
$children = $list.children(),
listLength = $children.length,
$objs = {
input: $this,
list: $list
};
if(code == 40){
if(listLength == 0) return;
var nowIndex = $list.find('.hover').index() + 1;
if(nowIndex >= listLength) nowIndex = 0;
}else if(code == 38){
if(listLength == 0) return;
var nowIndex = $list.find('.hover').index();
if(nowIndex < 0) nowIndex = 0;
nowIndex--;
if(nowIndex < 0) nowIndex = listLength - 1;
}else if(code == 13){
$list.hide();
if(typeof self.options.enter === 'function') self.options.enter.call(this, $objs);
return;
}else{
return;
}
$children.eq(nowIndex).addClass('hover').siblings().removeClass('hover');
var $li = $children.eq(nowIndex),
txt = $li.text();
$objs.selected = $li;
$this.val(txt);
if(typeof self.options.select === 'function') self.options.select.call(this, $objs);
});
});
$(document).on('click', function(e){
var $target = $(e.target),
$box = $target.closest('.ajax-input-coat');
if(!$box.length || $box.length && $target[0].tagName == 'INPUT' && $box.find('.list')[0].style.display == 'none'){
$('.ajax-input-coat .list').each(function(){
if($(this)[0].style.display != 'none'){
if(!$(this).find('.hover').length){
var $input = $(this).closest('.ajax-input-coat').find('input[type="text"]'),
$objs = {
input: $input,
list: $(this)
};
$input.val('');
if(typeof self.options.cancel === 'function') self.options.cancel.call(this, $objs);
}
$(this).hide();
return false;
}
});
}
});
}
});
Date.prototype.format = function(format) {
/**
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+" : this.getMonth() + 1, // month
"d+" : this.getDate(), // day
"h+" : this.getHours(), // hour
"m+" : this.getMinutes(), // minute
"s+" : this.getSeconds(), // second
"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
"S" : this.getMilliseconds()
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}