/**
* Utils工具类,用来扩展类似 jquery 的 utils $.xxx 扩展
* @author Lee 349238652@qq.com 大部分源代码来自 jQuery
*/
define(
'mk7/utils',
[
],
function() {
var $$ = Dom7;
var t7 = Template7;
var validateRegExp = {
decmal: "^([+-]?)\\d*\\.\\d+$",// 浮点数
decmal1: "^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$",// 正浮点数
decmal2: "^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$",// 负浮点数
decmal3: "^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",
// 浮点数
decmal4: "^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$",
// 非负浮点数(正浮点数 + 0)
decmal5: "^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$",
// 非正浮点数(负浮点数 +
// 0)
intege: "^-?[1-9]\\d*$",
// 整数
intege1: "^[1-9]\\d*$",
// 正整数
intege2: "^-[1-9]\\d*$",
// 负整数
num: "^([+-]?)\\d*\\.?\\d+$",
// 数字
num1: "^[1-9]\\d*|0$",
// 正数(正整数 + 0)
num2: "^-[1-9]\\d*|0$",
// 负数(负整数 + 0)
ascii: "^[\\x00-\\xFF]+$",
// 仅ACSII字符
chinese: "^[\\u4e00-\\u9fa5]+$",
// 仅中文
color: "^[a-fA-F0-9]{6}$",
// 颜色
date: "^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$",
// 日期
email: "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$",
// 邮件
idcard: "^[1-9]([0-9]{14}|[0-9]{17})$",
// 身份证
ip4: "^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$",
// ip地址
letter: "^[A-Za-z]+$",
// 字母
letter_l: "^[a-z]+$",
// 小写字母
letter_u: "^[A-Z]+$",
// 大写字母
mobile: "^0?(13|15|16|18|14|17|19)[0-9]{9}$", //^1[3|4|5|7|8]\d{9}$
// 手机
notempty: "^\\S+$",
// 非空
password: "^.*[A-Za-z0-9\\w_-]+.*$",
// 密码
fullNumber: "^[0-9]+$",
// 数字
picture: "(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$",
// 图片
qq: "^[1-9]*[1-9][0-9]*$",
// QQ号码
rar: "(.*)\\.(rar|zip|7zip|tgz)$",
// 压缩文件
tel: "^[0-9\-()()]{7,18}$",
// 电话号码的函数(包括验证国内区号,国际区号,分机号)
url: "^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$",
// url
username: "^[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+$",
// 用户名
deptname: "^[A-Za-z0-9_()()\\-\\u4e00-\\u9fa5]+$",
// 单位名
zipcode: "^\\d{6}$",
// 邮编
realname: "^[A-Za-z\\u4e00-\\u9fa5]+$",
// 真实姓名
addr: "^[A-Za-z0-9_()()\\#\\-\\u4e00-\\u9fa5]+$",
siteurl: "^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%=]*)?$",
strnamecontent: "^[0-9A-Za-z\\u4e00-\\u9fa5]+$",
strcontent: "^[0-9A-Za-z\\u4e00-\\u9fa5\\/\\\\]+$",
strslogancontent: "^[0-9A-Za-z\\u4e00-\\u9fa5\\@\\…\\;\\,\\,\\;\\……\\.\\。\\:\\:\\/\\\\]+$",
};
var utils = {
isZipcode: function(str){
return new RegExp(validateRegExp.zipcode).test(str);
},
isAmount: function(str){
return (new RegExp(validateRegExp.decmal4).test(str)) || (new RegExp(validateRegExp.intege1).test(str));
},
isEmpty: function(a) {
return typeof(a)=='undefined' || !a || a == '0'|| (a==null)
//return new RegExp("^[\\s+]*$").test(a)
},
isChinese: function(a) {
return new RegExp("^[\\u4e00-\\u9fa5]+$").test(a)
},
isLetter: function(a) {
return new RegExp("^[A-Za-z]+$").test(a)
},
isNumeric: function(a) {
return new RegExp("^([+-]?)\\d*\\.?\\d+$").test(a)
},
isBetweenLength: function(str, _min, _max) {
return (str.length >= _min && str.length <= _max);
},
isUsername: function(str) {
return new RegExp(validateRegExp.username).test(str);
},
isFullNumberName: function(str) {
return new RegExp(validateRegExp.fullNumber).test(str);
},
isPassword: function(str) {
return /^.*([\W_a-zA-z0-9-])+.*$/i.test(str);
},
isEmail: function(str) {
return new RegExp(validateRegExp.email).test(str);
},
isTelephone: function(str) {
return new RegExp(validateRegExp.tel).test(str);
},
isMobile: function(str) {
return new RegExp(validateRegExp.mobile).test(str);
},
isRealName: function(str) {
return new RegExp(validateRegExp.realname).test(str);
},
isAddress: function(str) {
return new RegExp(validateRegExp.addr).test(str);
},
isSiteUrl: function(str) {
return new RegExp(validateRegExp.siteurl).test(str);
},
isIdCard: function(str) {
return new RegExp(validateRegExp.idcard).test(str);
},
isStrContent: function(str) {
return new RegExp(validateRegExp.strcontent).test(str);
},
isStrNameContent: function(str) {
return new RegExp(validateRegExp.strnamecontent).test(str);
},
isStrSloganContent: function(str) {
return new RegExp(validateRegExp.strslogancontent).test(str);
},
};
var toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var class2type = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Object]' : 'object'
};
utils.type = function(obj) {
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
};
utils.isArray = function (obj) {
return utils.type(obj) === "array";
}
utils.isWindow = function(obj) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
utils.isFunction = function (obj) {
return utils.type(obj) === "function";
}
utils.isPlainObject = function (obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || utils.type(obj) !== "object" || obj.nodeType || utils.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch (e) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
}
utils.extend = function() {
// 定义默认参数和变量
// 对象分为扩展对象和被扩展的对象
//options 代表扩展的对象中的方法
//name 代表扩展对象的方法名
//i 为扩展对象参数起始值
//deep 默认为浅复制
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
//当第一个参数为布尔类型是,次参数定义是否为深拷贝
//对接下来的参数进行处理
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// 当定义是否深拷贝时,参数往后移动一位
i = 2;
}
//如果要扩展的不是对象或者函数,则定义要扩展的对象为空
if ( typeof target !== "object" && !utils.isFunction(target) ) {
target = {};
}
//当只含有一个参数时,被扩展的对象是jQuery或jQuery.fn
if ( length === i ) {
target = this;
--i;
}
//对从i开始的多个参数进行遍历
for ( ;i < length; i++ ) {
// 只处理有定义的值
if ( (options = arguments[ i ]) != null ) {
// 展开扩展对象
for ( name in options ) {
src = target[name];
copy = options[name];
// 防止循环引用
if ( target === copy ) {
continue;
}
// 递归处理深拷贝
if ( deep && copy && ( utils.isPlainObject(copy) || (copyIsArray = utils.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && utils.isArray(src) ? src : [];
} else {
clone = src && utils.isPlainObject(src) ? src : {};
}
target[name] = utils.extend( deep, clone, copy );
// 不处理未定义值
} else if ( copy !== undefined ) {
//给target增加属性或方法
target[name] = copy;
}
}
}
}
return target;
}
utils.isDefined = function(value) {
return typeof value !== 'undefined';
}
utils.inArray = function( elem, arr) {
for (var i in arr) {
if ( arr[i] === elem ) {
return true;
}
}
return false;
};
!function(){
var POPUP_TPL = '
';
/**
* @type {{stackPushDelay: number}}
*/
var config = {
stackPushDelay: 0
};
var popupStack = [];
var $toast = {
/**
* info方式是显示提示框之后,默认延迟1000ms小时,也可以自定义延迟消失的时间.
*/
show: showPopup,
/**
* @private for testing
*/
_createPopup: createPopup,
_popupStack: popupStack
};
utils.toast = $toast.show;
function createPopup(options) {
options = utils.extend({
closeDelay: 1500
}, options || {});
var self = {};
self.closeDelay = options.closeDelay;
var compiled = t7.compile(POPUP_TPL);
var elementHtml = compiled({content: options.content});
self.element = $$(elementHtml);
$$('body').append(self.element);
self.show = function() {
if (self.isShown || self.removed)
return;
self.isShown = true;
if (!self.isShown)
return;
$$.requestAnimationFrame(function(){
self.element.removeClass('toast-hidden');
self.element.addClass('toast-showing');
});
};
self.hide = function(callback) {
callback = callback || {};
if (!self.isShown) return callback();
self.isShown = false;
self.element.removeClass('toast-showing');
self.element.addClass('toast-hidden');
setTimeout(callback, 250, false);
};
self.remove = function() {
if (self.removed) return;
self.hide(function() {
self.element.remove();
});
self.removed = true;
};
return self;
}
function showPopup(options) {
var popup = $toast._createPopup(options);
var showDelay = 0;
if (popupStack.length > 0) {
showDelay = config.stackPushDelay;
setTimeout(popupStack[popupStack.length - 1].hide, showDelay, false);
} else {
//Add popup-open & backdrop if this is first popup
$$('body').addClass('toast-open');
}
_show();
function _show() {
popupStack.push(popup);
setTimeout(popup.show, showDelay, false);
setTimeout(function(){
var index = popupStack.indexOf(popup);
if (index !== -1) {
popupStack.splice(index, 1);
}
popup.remove();
if (popupStack.length > 0) {
popupStack[popupStack.length - 1].show();
} else {
//如果是最后一个弹窗, 移除 popup-open & 锁屏
setTimeout(function() {
if (!popupStack.length) {
$$('body').removeClass('toast-open');
}
}, 400, false);
}
}, popup.closeDelay);
}
}
}();
utils.csrf = function(data){
data = utils.extend({}, data);
var d = new Object();
var p = $$("[name='csrf-param']").attr('content');
var t = $$("[name='csrf-token']").attr('content');
d[p] = t;
return utils.extend(d, data);
}
utils.generateNonceStr = function (len){
// 密码字符集,可任意添加你需要的字符
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var str = "";
var charsLen = chars.lewngth;
if((len*1)<1){
len = 8;
}
for(var i = 0; i < len; i++)
{
str += chars[Math.floor(Math.random() * (charsLen-1))];
}
return str;
}
utils.ls = {
getDefaultKeu:function(){
return 'jw'+ utils.generateNonceStr(16);
},
get: function() {
var key = arguments[0]?arguments[0]:this.getDefaultKeu()
return window.JSON.parse(window.localStorage.getItem(key) || '[]')
},
set: function(items) {
var key = arguments[1]?arguments[1]:this.getDefaultKeu()
window.localStorage.setItem(key, window.JSON.stringify(items))
},
del:function(){
var key = arguments[0]?arguments[0]:this.getDefaultKeu()
window.localStorage.removeItem(key)
},
clear:function(){
window.localStorage.clear()
}
}
utils.backdrop = {
element : $$(''),
backdropHolds : 0,
retain : function() {
var me = this;
$$('body').append(me.element);
me.element = $$('.backdrop');
me.backdropHolds++;
if (me.backdropHolds === 1) {
me.element.addClass('visible');
setTimeout(function(){
if (me.backdropHolds >= 1) me.element.addClass('active');
});
}
},
release : function() {
var me = this;
if (me.backdropHolds === 1) {
me.element.removeClass('active');
setTimeout(function() {
// If we're still at 0 backdropHolds after async...
if (me.backdropHolds === 0) me.element.removeClass('visible');
}, 400, false);
}
me.backdropHolds = Math.max(0, me.backdropHolds - 1);
}
}
utils.getViewLogisUrl = function(options){
var url = "http://m.kuaidi100.com/index_all.html?type=" + options.apiCode + "&postid=" + options.trackingNo + "&callbackurl=" + options.callbackurl;
return url;
}
utils.trim=function(t){
return (t||"").replace(/^\s+|\s+$/g, "");
}
utils.getRad = function (d){
var PI = Math.PI;
return d*PI/180.0;
}
/**
* approx distance between two points on earth ellipsoid
* @param {Object} lat1
* @param {Object} lng1
* @param {Object} lat2
* @param {Object} lng2
*/
utils.getPointsDistance = function(lat1, lng1, lat2, lng2){
var me = this
var radLat1 = utils.getRad(lat1);
var radLat2 = utils.getRad(lat2);
var a = radLat1 - radLat2;
var b = utils.getRad(lng1) - utils.getRad(lng2);
var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s = s * 6378137.0;
s = Math.round(s*10000)/10000.0;
return s;
}
utils.cookie={
pre:function(){
return 'i8diejwe_';
},
get:function(name){
var me=this;
name=me.pre()+name;
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
},set:function(name,value){
var me=this;
var exp = new Date();
var hours = arguments[2] ? arguments[2] : (24*7);
name=me.pre()+name;
exp.setTime(exp.getTime() + hours*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
},del:function(name){
var me=this;
name=me.pre()+name;
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=this.get(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
}
utils.myAlert=function(content){
// 这里是单一alert 无关闭状态
if(content=='' || content==null){return false;}
var alert_tpl = '
';
$$('.myalertbox').remove();
var alertDom=$$(alert_tpl);
alertDom.click(function(e){
$(this).remove();
})
$$('body').append(alertDom);
}
utils.makePhone = function (object, phone){
setTimeout(function(){
var exitPhoneDom = object.find('.makephonecls');
console.log('makePhone')
if (exitPhoneDom.length > 0) {
exitPhoneDom.attr('href','tel:'+phone);
exitPhoneDom.click();
} else {
var phoneDom = $$('
')
object.append(phoneDom)
phoneDom.click()
}
},300)
}
utils.showIndicator = function () {
$$('body').append('
');
};
utils.showIndicatormsg = function (msgage) {
$$('body').append('
');
};
utils.hideIndicator = function () {
$$('.preloader-indicator-overlay, .preloader-indicator-modal').remove();
};
utils.httpGet = function(url,data,fun){
var me = this;
var showLoading = (true ===arguments[3]) ? true: arguments[3] ;
$$.ajax({
method : "GET",
url: url,
data: data,
dataType : "json",
beforeSend : function(){
if ( true == showLoading ) {
me.showIndicator();
}
},
success : function(res){
fun(res);
},
error : function(res){},
complete : function(res){
if ( true == showLoading ) {
me.hideIndicator();
}
}
});
}
utils.httpPost = function(url,data,fun){
var me = this;
var showLoading = (true === arguments[3]) ? true: arguments[3] ;
$$.ajax({
method : "POST",
url: url,
data: data,
dataType : "json",
beforeSend : function(){
if ( true == showLoading ) {
me.showIndicator();
}
},
success : function(res){
fun(res);
},
error : function(res){},
complete : function(res){
if ( true == showLoading ) {
me.hideIndicator();
}
}
});
}
utils.isWeixin = function() { // 是否微信浏览器
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
}
return utils;
}
);