Files
g.hnyhua.cn/Mtxfw.VipSite/Scripts/module.base.js

5334 lines
218 KiB
JavaScript
Raw Normal View History

/// <reference path="/global/script/lib/jquery-1.9.0.js" />
/**
*
* module.base.js
*
* 基础模块文件
*
* version 1.0.3.2(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年7月14日14:46:19
*
* last update 2014年9月30日09:57:28
*
*/
//JSON2
if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ':' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ':' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());
//创建函数原型方法
Function.prototype.Method = function (name, handle) {
/// <summary>
/// 创建函数原型方法
/// </summary>
/// <param name="name" type="String">函数名称</param>
/// <param name="handle" type="Function/JSON Object">操作对象</param>
/// <returns type="Object" />当前对象
this.prototype[name] = handle;
return this;
};
//函数继承
Function.prototype.extend = function (extendFn) {
/// <summary>
/// 函数继承
/// </summary>
/// <param name="extendFn" type="Function">被继承函数</param>
/// <returns type="Object" />当前对象
if (extendFn) {
this.prototype = extendFn.prototype;
}
return this;
};
//添加创建全局(公共)对象(或函数)
window.Global = window.Global || new Object();
//创建添加全局对象(对象将被添加到window对象下以作为任何地方都可访问的全局对象)
Global.Add = function (name, handle) {
/// <summary>
/// 创建添加公共方法的函数(函数将被添加到window对象下以作为任何地方都可访问的公共函数)
/// </summary>
/// <param name="name" type="String">名称</param>
/// <param name="handle" type="Function/Object">操作对象可以是函数也可以是JSON对象</param>
/// <returns type="Object" />当前对象
window[name] = handle;
return this;
};
; (function () {
//去掉字符串中间的空格(包括开始和结束)
String.Method('trim', function (str) {
/// <summary>去掉字符串中间的空格(包括开始和结束)</summary>
/// <param name="str" type="String">自定义需要将空格替换成什么字符(选填,默认为为空字符[""],即是去掉空格)</param>
/// <returns type="String" />替换后的字符串
return this.toString().replace(/[ ]/g, str || '');
});
//去掉字符串开始的空格
String.Method('lTrim', function (str) {
/// <summary>去掉字符串开始的空格</summary>
/// <param name="str" type="String">自定义需要将空格替换成什么字符(选填,默认为为空字符[""],即是去掉空格)</param>
/// <returns type="String" />替换后的字符串
return this.toString().replace(/(^\s*)/g, str || '');
});
//去掉字符串结束的空格
String.Method('rTrim', function (str) {
/// <summary>去掉字符串结束的空格</summary>
/// <param name="str" type="String">自定义需要将空格替换成什么字符(选填,默认为为空字符[""],即是去掉空格)</param>
/// <returns type="String" />替换后的字符串
return this.toString().replace(/(\s*$)/g, str || '');
});
//替换所有
String.Method('replaceAll', function (beRep, rep) {
/// <summary>替换所有</summary>
/// <param name="beRep" type="String">被替换字符串</param>
/// <param name="rep" type="String">替换字符串</param>
/// <returns type="String" />替换后的字符串
return this.replace(new RegExp(beRep, "gm"), rep);
});
//截取字符串,超过指定长度以"..."代替(默认,可自定义)
String.Method('subString', function (subLength, strReplace) {
/// <summary>截取字符串,超过指定长度以"..."代替(默认,可自定义)</summary>
/// <params name="subLength" type="Int">需要截取字符串的长度</params>
/// <params name="strReplace" type="String">截取字符串,超过指定长度以"..."代替(默认,可自定义),该参数就是用户自定义的字符或字符串</params>
/// <returns type="String" />截取后的字符串
var that = this.toString();
return (that.length > subLength && subLength) ? (that.substring(0, subLength) + (strReplace ? strReplace : "...")) : (that);
});
//获取字符串中的'{=}'字符
String.Method('regMatch', function (reg) {
/// <summary>获取字符串中的'{=}'字符</summary>
/// <params name="reg" type="String">自定义正则</params>
/// <returns type="Array" />获取到的字符集合
reg = reg || /\{=[^\}]+\}/g;
return this.toString().match(reg);
});
//判断是否为数组
Global.Add('isArray', function (ary) {
/// <summary>判断是否为数组</summary>
/// <param name="ary" type="Array">数组对象</param>
/// <returns type="Boolean" />是否为数组(true.数组 false.非数组)
try {
return Object.prototype.toString.call(ary) === "[object Array]";
} catch (e) {
return false;
}
});
//判断是否为JSON
Global.Add('isJSON', function (json) {
/// <summary>判断是否为JSON</summary>
/// <param name="json" type="Object">JSON对象</param>
/// <returns type="Boolean" />是否为JSON(true.JSON false.非JSON)
try {
return (typeof (json) == "object" && Object.prototype.toString.call(json).toLowerCase() == "[object object]" && !json.length);
} catch (e) {
return false;
}
});
//判断是否为函数
Global.Add('isFunction', function (fun) {
/// <summary>判断是否为函数</summary>
/// <param name="fun" type="Function">函数对象</param>
/// <returns type="Boolean" />是否为函数(true.函数 false.非函数)
return typeof (fun) === 'function';
});
//判断是否为字符串
Global.Add('isString', function (str) {
/// <summary>判断是否为字符串</summary>
/// <param name="str" type="String">字符串</param>
/// <returns type="Boolean" />是否为字符串(true.字符串 false.非字符串)
return typeof (str) === 'string';
});
//判断是否为数字
Global.Add('isNumber', function (num) {
/// <summary>判断是否为数字</summary>
/// <param name="num" type="Int">数字</param>
/// <returns type="Boolean" />是否为数字(true.数字 false.非数字)
return !isNaN(num);
});
//判断是否为Boolean类型
Global.Add('isBoolean', function (bool) {
/// <summary>判断是否为Boolean类型</summary>
/// <param name="bool" type="Boolean">boolean</param>
/// <returns type="Boolean" />是否为Boolean类型(true.boolean类型 false.非boolean类型)
try {
return (typeof (eval(bool)) == 'boolean');
} catch (e) { }
return false;
});
//判断是否为Url
Global.Add('isUrl', function (url) {
/// <summary>判断是否为Url</summary>
/// <param name="url" type="String">需要判断的字符串</param>
/// <returns type="Boolean" />是否为Url(true.Url false.非Url)
var reg = /^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/;
return new RegExp(reg).test(url);
});
//判断浏览器类型是否为360
Global.Add('is360', function () {
/// <summary>判断浏览器类型是否为360</summary>
/// <returns type="Boolean" />是否为360
var result = false;
if (window.navigator.userAgent.toLowerCase().indexOf("360se") >= 1) { result = true; }
if (window.external && window.external.twGetRunPath) {
var runPath = external.twGetRunPath();
if (runPath && runPath.toLowerCase().indexOf("360se") > -1) { result = true }
}
return result;
});
//判断是否为'false',不论是字符串还是布尔类型
Global.Add('isFalse', function (value) {
/// <summary>判断是否为'false',不论是字符串还是布尔类型</summary>
/// <param name="value" type="String/Boolean">需要判断的值</param>
/// <returns type="Boolean" />不论是字符串还是布尔类型不区分大小写只要为false则返回true否则返回false
return value != null && value != undefined ? value.toString().toLocaleLowerCase() === 'false' ? true : false : false;
});
//判断是否为'true',不论是字符串还是布尔类型
Global.Add('isTrue', function (value) {
/// <summary>判断是否为'true',不论是字符串还是布尔类型</summary>
/// <param name="value" type="String/Boolean">需要判断的值</param>
/// <returns type="Boolean" />不论是字符串还是布尔类型不区分大小写只要为true则返回true否则返回false
return value ? value.toString().toLocaleLowerCase() === 'true' ? true : false : false;
});
//判断元素对象(默认为浏览器对象)是否出现滚动条
Global.Add('isScroll', function (target) {
/// <summary>判断一个元素对象(默认为浏览器对象)是否出现滚动条</summary>
/// <param name="target" type="Element">元素对象(默认为body)</param>
/// <returns type="JSON">{x: 下(true:有 false:无), y: 右(true:有 false:无)}
//初始化变量值
target = target ? (target.length ? target : [target]) : [document.documentElement, document.body];
var xStatus = false, yStatus = false;
var i = 0, length = target.length, element, scrollLeft, scrollTop;
for (; i < length; i++) {
element = target[i];
//获取scrollLeft
scrollLeft = element.scrollLeft;
element.scrollLeft += scrollLeft > 0 ? -1 : 1;
element.scrollLeft !== scrollLeft && (xStatus = xStatus || true);
element.scrollLeft = scrollLeft;
//获取scrollTop
scrollTop = element.scrollTop;
element.scrollTop += scrollTop > 0 ? -1 : 1;
element.scrollTop !== scrollTop && (yStatus = yStatus || true);
element.scrollTop = scrollTop;
}
return { x: xStatus, y: yStatus };
});
//获取元素对象(默认为浏览器对象)滚动条距顶部的距离和距左边的距离
Global.Add('getScroll', function (target) {
/// <summary>获取滚动条距顶部的距离和距左边的距离</summary>
/// <param name="target" type="Element">元素对象(默认为body)</param>
/// <returns type="JSON">{left: 横向滚动条距左边的距离, top: 纵向滚动条距上边的距离}
var x, y;
if (target) {
target = target.length ? target[0] : target;
x = target.scrollLeft;
y = target.scrollTop;
}
else {
if (window.pageYOffset) {
x = window.pageXOffset;
y = window.pageYOffset;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
x = document.documentElement.scrollLeft || document.body.scrollLeft;
y = document.documentElement.scrollTop || document.body.scrollTop;
}
else if (document.body) {
x = document.body.scrollLeft;
y = document.body.scrollTop;
}
}
return { left: x, top: y };
});
//获取元素对象(默认为浏览器对象)的宽和高(可操作区域,包括滚动条内所有内容)
Global.Add('scrollSize', function (target) {
/// <summary>获取元素对象(默认为浏览器对象)的宽和高(可操作区域,包括滚动条内所有内容)</summary>
/// <param name="target" type="Element">元素对象(默认为body)</param>
/// <returns type="JSON">{width: 宽, height: 高}
var height, width;
if (target) {
target = target.length ? target[0] : target;
var offsetHeight = target.offsetHeight,
scrollHeight = target.scrollHeight;
height = scrollHeight > offsetHeight ? scrollHeight : offsetHeight;
var offsetWidth = target.offsetWidth,
scrollWidth = target.scrollWidth;
width = scrollWidth > offsetWidth ? scrollWidth : offsetWidth;
}
else {
var clientHeight = document.documentElement.clientHeight;
var offsetHeight = document.body.offsetHeight;
var docHeight = document.documentElement.offsetHeight;
var scrollHeight = document.body.scrollHeight;
height = offsetHeight >= clientHeight ? offsetHeight : clientHeight;
height = height < docHeight ? docHeight : height;
height = height < scrollHeight ? scrollHeight : height;
clientWidth = document.documentElement.clientWidth;
offsetHeight = document.body.offsetWidth;
docHeight = document.documentElement.offsetWidth;
scrollHeight = document.body.scrollWidth;
width = offsetHeight >= clientWidth ? offsetHeight : clientWidth;
width = width < docHeight ? docHeight : width;
width = width < scrollHeight ? scrollHeight : width;
}
return { width: width, height: height };
});
//获取元素对象(默认为浏览器对象)的宽和高(可见区域,不包括滚动条内所有内容)
Global.Add('clientSize', function (target) {
/// <summary>获取元素对象(默认为浏览器对象)的宽和高(可见区域,不包括滚动条内所有内容)</summary>
/// <param name="target" type="Element">元素对象(默认为body)</param>
/// <returns type="JSON">{width: 宽, height: 高}
var width = 0, height = 0;
if (target) {
target = target.length ? target[0] : target;
width = target.offsetWidth, height = target.offsetHeight;
}
else {
if (self.innerHeight && self.innerWidth) {
width = self.innerWidth, height = self.innerHeight;
}
else {
var documentElement = document.documentElement;
width = documentElement.clientWidth, height = documentElement.clientHeight;
}
}
return { width: width, height: height };
});
//时间线程模拟循环(提高遍历数据执行效率)
Global.Add('listEach', function (list, each, callBack) {
/// <summary>时间线程模拟循环(提高遍历数据执行效率)</summary>
/// <param name="list" type="Array List">遍历的数据集合</param>
/// <param name="each" type="Function">遍历时回调函数</param>
/// <param name="callBack" type="Function">遍历完成时回调函数</param>
var i = 0, length = list.length, item;
if (length) {
var listThread = window.setInterval(function () {
item = list[i];
if (isFunction(each)) {
each.call(item, i);
}
i++;
if (i >= length) {
window.clearInterval(listThread);
listThread = null;
if (isFunction(callBack)) {
callBack.call(list, length);
}
}
}, 1);
}
});
//判断浏览器类型
Global.Add('browser', function () {
/// <summary>获取浏览器类型及版本</summary>
/// <returns type="Object" />浏览器类型信息
var typeInfo = {}, userAgent = navigator.userAgent.toLowerCase(), info;
(info = userAgent.match(/msie ([\d.]+)/)) ? typeInfo.ie = info[1] :
(info = userAgent.match(/firefox\/([\d.]+)/)) ? typeInfo.firefox = info[1] :
(info = userAgent.match(/chrome\/([\d.]+)/)) ? typeInfo.chrome = info[1] :
(info = userAgent.match(/opera.([\d.]+)/)) ? typeInfo.opera = info[1] :
(info = userAgent.match(/version\/([\d.]+).*safari/)) ? typeInfo.safari = info[1] : 0;
return typeInfo;
});
//密码强度验证(类型:数字、大写字母、小写字母、特殊字符)
Global.Add('evaluate', function (word, lens) {
/// <summary>密码强度验证(类型:数字、大写字母、小写字母、特殊字符)</summary>
/// <param name="word" type="String">密码字符串</param>
/// <param name="lens" type="Int">密码长度</param>
/// <returns type="Int" />返回密码强度级别
if (lens != undefined) {
lens = lens || 6;
}
else {
lens = 1;
}
//CharMode函数
//测试某个字符是属于哪一类.
var CharMode = function (iN) {
if (iN >= 48 && iN <= 57) //数字
return 1;
if (iN >= 65 && iN <= 90) //大写字母
return 2;
if (iN >= 97 && iN <= 122) //小写
return 4;
else
return 8; //特殊字符
};
//bitTotal函数
//计算出当前密码当中一共有多少种模式
var bitTotal = function (num) {
modes = 0;
for (i = 0; i < 4; i++) {
if (num & 1) modes++;
num >>>= 1;
}
return modes;
};
//checkStrong函数
//返回密码的强度级别
var checkStrong = function (sPW) {
if (sPW.length < lens)
return 0; //密码太短
Modes = 0;
for (i = 0; i < sPW.length; i++) {
//测试每一个字符的类别并统计一共有多少种模式.
Modes |= CharMode(sPW.charCodeAt(i));
}
return bitTotal(Modes);
};
return checkStrong(word);
});
//获取事件的目标元素
Global.Add('eventTarget', function (e) {
/// <summary>获取事件的目标元素</summary>
/// <param name="e" type="Event">Event对象</param>
/// <returns type="Element" />目标元素
e = e || window.event;
return e.target || e.srcElement || arguments.callee.caller.arguments[0];
});
//获取事件坐标
Global.Add('eventCoordinates', function (e) {
/// <summary>获取事件坐标</summary>
/// <param name="e" type="Event">Event对象</param>
/// <returns type="JSON Object" />坐标对象
var coor = { x: 0, y: 0 };
e = e || window.event;
coor.x = e.clientX, coor.y = e.clientY;
return coor;
});
//阻止浏览器的默认行为
Global.Add('stopDefault', function (e) {
e = e || window.event;
//如果提供了事件对象则这是一个非IE浏览器
if (e && e.preventDefault) {
//阻止默认浏览器动作(W3C)
e.preventDefault();
} else {
//IE中阻止函数器默认动作的方式
try {
if (e.returnValue) {
e.returnValue = false;
}
} catch (e) {
}
}
return false;
});
//停止事件冒泡
Global.Add('stopBubble', function (e) {
e = e || window.event;
//如果提供了事件对象则这是一个非IE浏览器
if (e && e.stopPropagation) {
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
} else {
//否则我们需要使用IE的方式来取消事件冒泡
e.cancelBubble = true;
}
return false;
});
//设置元素透明度
Global.Add('opacity', function (target, opacity) {
/// <summary>设置元素透明度</summary>
/// <param name="target" type="Element">目标元素</param>
/// <param name="opacity" type="Number">透明度(取值为0~1之间)</param>
target = $(target);
target.css('filter', 'alpha(opacity=' + (opacity * 100) + ')')
.css('-moz-opacity', opacity)
.css('-khtml-opacity', opacity)
.css('opacity', opacity);
});
//等比例缩放
Global.Add('suchAsScaling', function (opts) {
opts = opts || {};
var options = {
//原始宽度
width: opts.width || 10,
//原始高度
height: opts.height || 10,
//最大宽度
maxWidth: opts.maxWidth || 100,
//最大高度
maxHeight: opts.maxHeight || 100
};
var width = options.width, height = options.height,
maxWidth = options.maxWidth, maxHeight = options.maxHeight,
resultWidth = width, resultHeight = height,
rate = 0;
if (height > maxHeight && width < maxWidth) {
resultHeight = maxHeight;
rate = width > height ? height / width : width / height;
resultWidth = (((height - maxHeight) / height) * width) * rate;
}
else if (width > maxWidth && height < maxHeight) {
resultWidth = maxWidth;
rate = width > height ? height / width : width / height;
resultHeight = (((width - maxWidth) / width) * height) * rate;
}
else if (width > maxHeight && height > maxHeight) {
if (width > height) {
resultWidth = maxWidth;
resultHeight = ((maxWidth / width) * height) * (height / width);
}
else {
resultHeight = maxHeight;
resultWidth = ((maxHeight / h) * w) * (width / h);
}
}
var marginLeft = 0, marginTop = 0;
if (resultWidth < maxWidth) {
marginLeft = (maxWidth - resultWidth) / 2;
}
if (resultHeight < maxHeight) {
marginTop = (maxHeight - resultHeight) / 2;
}
return { width: resultWidth, height: resultHeight, marginTop: marginTop, marginLeft: marginLeft };
});
})();
; (function () {
/// <summary>
/// 创建模块对象
/// </summary>
var TheModule = function () {
/// <summary>
/// 模块对象
/// </summary>
var that = this;
//identity
that.identity = 0;
//版本
that.version = '1.0.3.2';
//作者
that.author = 'pye-mail@163.com';
//更新历史
that.history = [
{ date: '2015年3月10日14:18:25', handle: '创建', remark: '创建O2O WebApp base' }
];
//模块加载完成
that.loadComplete = true;
//基础地址
that.basePath = '/global/script/module/';
var ModelGroup = new Object();
//GUID.全局唯一标识符
TheModule.Method('Guid', function (prefix) {
/// <summary>
/// GUID.全局唯一标识符
/// </summary>
/// <param name="prefix" type="String">前缀</param>
/// <returns type="String" />前缀(prefix) + GUID
var result = prefix ? (prefix + that.identity) : that.identity;
that.identity += 1;
return result;
});
//创建模块
TheModule.Method('Create', function (name, handle) {
/// <summary>
/// 创建模块
/// </summary>
/// <param name="name" type="String">模块名称</param>
/// <param name="handle" type="Function/JSON Object">操作函数/对象</param>
ModelGroup[name] = handle;
});
//引用模块
TheModule.Method('Use', function (name, arguments, callBack) {
/// <summary>
/// 创建模块
/// </summary>
/// <param name="name" type="String">模块名称</param>
/// <param name="callBack" type="Function">回调函数</param>
var ModelHandle = ModelGroup[name],
ModelResult;
if (ModelHandle) {
if (typeof (arguments) == 'function') {
callBack = arguments;
arguments = null;
}
ModelResult = new ModelHandle(arguments);
if (callBack) {
//callBack.call(ModelHandle, ModelResult);
callBack(ModelHandle, ModelResult);
}
}
else {
var msg = "Cannot find module '" + name + "'";
alert(msg);
Module.Error(msg);
}
return ModelResult;
});
//加载(模块文件[JS文件])
TheModule.Method('Require', function (path, callBack) {
/// <summary>
/// 加载(模块文件[JS文件])
/// </summary>
/// <param name="path" type="String/Array">模块名或集合</param>
/// <param name="callBack" type="Function">回调函数</param>
if (path) {
var pathArray = [];
if (isString(path)) {
pathArray.push(path);
}
else if (isArray(path)) {
pathArray = path;
}
else {
return false;
}
var flag = false;
if (callBack) {
if (isBoolean(callBack)) {
flag = callBack;
callBack = null;
}
}
var isBrowser = !!(typeof window !== 'undefined' && navigator && document);
var isWebWorker = !isBrowser && typeof importScripts !== 'undefined';
var isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]';
var readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/
var head = document.getElementsByTagName('head')[0], scriptTarget, scriptID;
var i = 0, length = pathArray.length, pathItem, src, count = 0;
var scriptLoad = function (event) {
if (event.type === 'load' || (readyRegExp.test((event.currentTarget || event.srcElement).readyState))) {
count++;
if (count == length) {
if (callBack) {
callBack.call(this);
}
}
}
};
for (; i < length; i++) {
pathItem = pathArray[i];
scriptID = 'J-require-#MODULE#'.replace('#MODULE#', pathItem);
scriptTarget = document.getElementById(scriptID);
if (scriptTarget) {
count++;
if (count == length) {
if (callBack) {
callBack.call(this);
}
}
}
else {
if (flag) {
src = pathItem;
}
else {
src = that.basePath + pathItem + '.js';
}
scriptTarget = document.createElement('script');
scriptTarget.type = 'text/javascript';
scriptTarget.charset = 'utf-8';
scriptTarget.async = true;
scriptTarget.setAttribute('data-module', pathItem);
scriptTarget.setAttribute('id', scriptID);
if (isBrowser) {
if (scriptTarget.attachEvent && !(scriptTarget.attachEvent.toString && scriptTarget.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) {
scriptTarget.attachEvent('onreadystatechange', scriptLoad);
} else {
scriptTarget.addEventListener('load', scriptLoad, false);
}
scriptTarget.src = src;
head.appendChild(scriptTarget);
}
else if (isWebWorker) {
importScripts(src);
scriptLoad();
}
}
}
}
});
//保存RequireCallBack事件
TheModule.Method('onRequireCallBack', function (callBack) {
if (callBack) {
that.customCallBack = that.customCallBack || {};
that.customCallBack['onRequireCallBack'] = callBack;
}
});
//响应RequireCallBack事件主要用于组合模块调用
TheModule.Method('getCustomCallBackEvent', function () {
var requireCallBack = that.customCallBack['onRequireCallBack'];
if (requireCallBack) {
requireCallBack();
}
that.customCallBack['onRequireCallBack'] = null;
});
//执行代码
TheModule.Method('Run', function (fun) {
if (fun) {
$(function () {
var pageHandle = {
//刷新本页面
refresh: function () {
/// <summary>
/// 刷新本页面
/// </summary>
var url = window.location.href;
window.location.href = url;
return pageHandle;
},
//在本页打开另一页面
jump: function (url, data) {
/// <summary>
/// 在本页打开另一页面
/// </summary>
/// <param name="url" type="String">跳转路径</param>
/// <param name="data" type="JSON Object">新页面所需数据</param>
if (url) {
if (data && isJSON(data)) {
var hasParam = url.indexOf('?'), firstSplit = '?', i = 0;
if (hasParam) {
firstSplit = '&';
}
for (var key in data) {
if (i == 0) {
url += firstSplit + key + '=' + data[key];
}
else {
url += '&' + key + '=' + data[key];
}
}
}
window.location.href = url;
}
return pageHandle;
},
//返回历史记录中上一次访问的页面
history: function (back) {
/// <summary>
/// 返回历史记录中上一次访问的页面
/// </summary>
/// <param name="back" type="Int">返回第几步,默认为-1上一步</param>
return pageHandle;
}
};
fun.call(pageHandle);
});
}
});
//异步请求完成后执行
TheModule.Method('AsyncRun', function (fun) {
if (fun) {
//异步执行操作
Module.asyncRunHandle = function () {
var tabID = GlobalTabID;
var pageHandle = {
//刷新本页面
refresh: function () {
/// <summary>
/// 刷新本页面
/// </summary>
return pageHandle;
},
//在本页打开另一页面
jump: function (path, data) {
/// <summary>
/// 在本页打开另一页面
/// </summary>
/// <param name="path" type="String">跳转路径</param>
/// <param name="title" type="String">跳转页面后标签标题</param>
/// <param name="data" type="JSON Object">新页面所需数据</param>
if (isJson(title)) {
data = title;
title = null;
}
return pageHandle;
},
//返回历史记录中上一次访问的页面
history: function (back) {
/// <summary>
/// 返回历史记录中上一次访问的页面
/// </summary>
/// <param name="back" type="Int">返回第几步,默认为-1上一步</param>
return pageHandle;
}
};
fun.call(pageHandle);
Module.asyncRunHandle = null;
};
}
});
//保存异步请求历史记录
TheModule.Method('AsyncHistory', function (options) {
var path = options.path;
var thisOptions = {};
thisOptions.tabID = tabID;
thisOptions.path = path;
thisOptions.title = options.title;
thisOptions.data = options.data;
NavTabsModelInstance.history = NavTabsModelInstance.history || {};
NavTabsModelInstance.history[tabID] = NavTabsModelInstance.history[tabID] || {
//所有历史记录页面地址
path: [],
//当前页位置
pageIdx: 0
};
var historyList = NavTabsModelInstance.history[tabID];
var pathList = historyList.path;
var i = 0, length = pathList.length, pathItem, flag = true;
for (; i < length; i++) {
pathItem = pathList[i];
if (pathItem.path == path) {
flag = false;
break;
}
}
if (flag) {
pathList.push(thisOptions);
historyList.pageIdx++;
}
});
//抛出错误消息
TheModule.Method('Error', function (msg) {
/// <summary>
/// 抛出错误消息
/// </summary>
/// <param name="msg" type="String">消息内容</param>
throw msg instanceof Error ? msg : new Error(msg);
});
//MediaQuery
TheModule.Method('onMediaQuery', function (width, callBack) {
var browserInfo = browser();
var mediaHandle = function () {
if (browserInfo.ie) {
var ieVersion = parseInt(browserInfo.ie);
if (ieVersion < 8) {
if (callBack && isFunction(callBack)) {
$(window).resize(function () {
var clientInfo = clientSize();
var clientWidth = clientInfo.width;
if (width) {
if (clientWidth < width) {
callBack.call(browserInfo, clientWidth);
}
}
else {
callBack.call(browserInfo, clientWidth);
}
});
}
}
}
};
if (isNumber(width)) {
mediaHandle();
}
else if (isFunction(width)) {
callBack = width;
width = null;
mediaHandle();
}
});
};
Global.Add('Module', new TheModule);
})();
/**
*
* 模拟线程
*
* version 1.0.2.0(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年7月14日14:12:44
*
* update log 2014年7月15日09:58:46
*
*/
Module.Create('Thread', function () {
/// <summary>
/// 模拟线程类
/// </summary>
/// <param name='fun' type='Function'>线程执行函数</param>
/// <param name='timer' type='Int'>线程执行间隔时间(单位:毫秒[1000毫秒 = 1秒])</param>
var that = this;
that.Thread = function (fun, timer) {
var that = this;
var startThread, timingStartThread, timingStopThread, suspendThread;
var ThreadModel = function (fun, timer) {
var that = this;
that.fun = fun;
that.timer = timer;
};
var clearAllThread = function () {
//清空启动中定时启动的线程
window.clearTimeout(timingStartThread),
timingStartThread = null;
//清空start线程
window.clearInterval(startThread),
startThread = null;
//清空暂停中的线程
window.clearTimeout(suspendThread),
suspendThread = null;
//清空定时停止线程
window.clearTimeout(timingStopThread),
timingStopThread = null;
};
var ThreadModelInstance = new ThreadModel(fun, timer);
//启动线程
that.start = function (timer) {
/// <summary>
/// 启动线程
/// </summary>
/// <param name='timer' type='Int'>启动线程的时间,即多少毫秒后启动,默认(不填时)为立即启动(单位:毫秒[1000毫秒 = 1秒])</param>
var that = this;
timer = timer || 0;
timingStartThread = window.setTimeout(function () {
clearAllThread();
//启动模拟线程
startThread = window.setInterval(ThreadModelInstance.fun, ThreadModelInstance.timer);
}, timer);
};
//停止线程
that.stop = function (timer) {
/// <summary>
/// 停止线程
/// </summary>
/// <param name='timer' type='Int'>停止线程的时间,即多少毫秒后停止,默认(不填时)为立即停止(单位:毫秒[1000毫秒 = 1秒])</param>
var that = this;
timer = timer || 0;
timingStopThread = window.setTimeout(function () {
clearAllThread();
}, timer);
};
//暂停线程
that.suspend = function (timer) {
/// <summary>
/// 暂停线程
/// </summary>
/// <param name='timer' type='Int'>暂停线程的时间,即多少毫秒后继续执行,默认(不填时)为1000(单位:毫秒[1000毫秒 = 1秒])</param>
var that = this;
timer = timer || 1000;
var againStart = that.start;
clearAllThread();
suspendThread = window.setTimeout(againStart, timer);
};
};
});
/**
*
* Touch 移动端Web触摸滑动事件模块
*
* version 1.0.2.2(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年8月30日15:01:55
*
* update log 2014年8月30日16:03:25
* 2014年9月9日14:37:30(兼容pc端(IE6,7,8,9)windows phone(IE1011)和androidios的触摸事件只需要和android,ios一样使用函数就可以了)
* 2014年10月14日09:36:41(修复低版本IE出错的Bug)
*
*/
Module.Create('Touch', function () {
/// <summary>
/// 移动端Web触摸滑动事件模块
/// </summary>
var that = this;
//函数封装(或包装)
var EncapsulationFunction = function (handle) {
/// <summary>
/// 函数封装(或包装),将传入的函数包装为我们需要的函数对象
/// </summary>
/// <param name="handle" type="JSON Object">函数对象</param>
var that = this;
//触摸开始函数
that.start = handle.start || null;
//触摸滑动函数
that.move = handle.move || null;
//触摸结束函数
that.end = handle.end || null;
};
//封装一个我们需要的触摸事件参数集合对象
var EncapsulationTouch = function (touch, event) {
/// <summary>
/// 封装一个我们需要的触摸事件参数集合对象
/// </summary>
/// <param name="touch" type="Object">Touch对象</param>
/// <param name="event" type="Event Object">触摸事件对象</param>
var that = this;
var count = 0;
if (touch) {
var i = 0, length = touch.length, touchItem;
for (; i < length; i++) {
//获取第i个手指的触摸事件相关参数
touchItem = touch[i];
if (touchItem) {
that['touch' + (i + 1)] = { x: touchItem.clientX, y: touchItem.clientY, event: event };
count++;
}
}
//保存当前触发触摸事件的手指个数
that['length'] = count;
}
else {
that['touch1'] = { x: event.clientX, y: event.clientY, event: event };
count = 1;
}
//保存当前触发触摸事件的手指个数
that['length'] = count;
};
//触摸滑动事件封装
that.TouchSlide = function (options) {
/// <summary>
/// 触摸基本事件
/// </summary>
/// <param name="options" type="JSON Object">参数对象</param>
/// <param name="handle" type="Function/JSON Object">操作函数(move)对象或集合</param>
var that = this;
var TouchSlideModel = function (model) {
var that = this;
that.target = $(model.target || document.body);
that.handle = model.handle;
that.preventDefault = isFalse(model.preventDefault) ? false : true;
};
var TouchSlideModelInstance = new TouchSlideModel(options || {});
var TouchEventType = function () {
var that = this;
that.MSPointerType = {
start: 'MSPointerOver',
move: 'MSPointerMove',
end: 'MSPointerOut'
};
that.pointerType = {
start: 'pointerover',
move: 'pointermove',
end: 'pointerout'
};
that.touchType = {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
};
that.mouseType = {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup',
out: 'mouseout'
};
};
var EventType = new TouchEventType();
var isTouch = function () {
return typeof window.ontouchstart !== 'undefined';
};
var isMSPointer = function () {
return window.navigator.msPointerEnabled;
};
var isPointer = function () {
return window.navigator.pointerEnabled;
};
var bindEvent = function (target, eventName, handle) {
if (target) {
if (isString(eventName)) {
target['on' + eventName] = handle;
}
else if (isArray(eventName)) {
var i = 0, length = eventName.length;
for (; i < length; i++) {
target['on' + eventName[i]] = handle[i];
}
}
}
};
var install = function () {
var handle = TouchSlideModelInstance.handle,
target = TouchSlideModelInstance.target,
preventDefault = TouchSlideModelInstance.preventDefault;
//封装基础操作函数
var baseHandle = new EncapsulationFunction(handle || {});
if (target) {
var touchStart, touchMove, touchEnd, touchFlag = false, moveTouchFlag = false;
//触摸开始事件
var startHandle = function (event) {
/// <summary>
/// 触摸开始事件
/// </summary>
/// <param name="e">Window Event</param>
event = event || window.event;
if (!touchFlag) {
//获取手指触摸移动对象
touchStart = new EncapsulationTouch(event.targetTouches, event);
if (baseHandle.start) {
//响应事件
baseHandle.start.call(this, touchStart);
}
var customEvent = that.customEvent;
if (customEvent) {
var touchStartEvent = customEvent.onTouchStart;
if (touchStartEvent && typeof (touchStartEvent) == 'function') {
touchStartEvent.call(this, touchStart);
}
}
//激活Touch状态
touchFlag = true;
this.onclick = function () {
moveTouchFlag = true;
$(this).mouseup();
};
//阻止内容(如图片、文字、链接等)被拖动
return false;
}
};
//触摸移动事件
var moveHandle = function (event) {
/// <summary>
/// 触摸移动事件
/// </summary>
/// <param name="event">Window Event</param>
event = event || window.event;
if (touchFlag) {
if (event.preventDefault) {
//touchmove事件加上preventDefault从而阻止触摸时浏览器的缩放、滚动条滚动等
event.preventDefault();
}
//获取手指触摸移动对象
touchMove = new EncapsulationTouch(event.touches, event);
var xDistance = touchStart.touch1.x - touchMove.touch1.x,
yDistance = touchStart.touch1.y - touchMove.touch1.y;
if (baseHandle.move) {
//响应事件
baseHandle.move.call(this, touchStart, touchMove, [xDistance, yDistance]);
}
var customEvent = that.customEvent;
if (customEvent) {
var touchMoveEvent = customEvent.onTouchMove;
if (touchMoveEvent && typeof (touchMoveEvent) == 'function') {
touchMoveEvent.call(this, touchStart, touchMove, [xDistance, yDistance]);
}
}
if (yDistance > 0) {
//向上滑动事件
if (customEvent) {
var slideUpEvent = customEvent.onSlideUp;
if (slideUpEvent && typeof (slideUpEvent) == 'function') {
slideUpEvent.call(this, touchStart, touchMove, yDistance);
}
}
}
else {
//向下滑动事件
if (customEvent) {
var slideDownEvent = customEvent.onSlideDown;
if (slideDownEvent && typeof (slideDownEvent) == 'function') {
slideDownEvent.call(this, touchStart, touchMove, yDistance);
}
}
}
if (xDistance > 0) {
//向左滑动事件
if (customEvent) {
var slideLeftEvent = customEvent.onSlideLeft;
if (slideLeftEvent && typeof (slideLeftEvent) == 'function') {
slideLeftEvent.call(this, touchStart, touchMove, xDistance);
}
}
}
else {
//向右滑动事件
if (customEvent) {
var slideRightEvent = customEvent.onSlideRight;
if (slideRightEvent && typeof (slideRightEvent) == 'function') {
slideRightEvent.call(this, touchStart, touchMove, xDistance);
}
}
}
moveTouchFlag = true;
}
};
//触摸结束事件
var endHandle = function (event) {
/// <summary>
/// 触摸结束事件
/// </summary>
/// <param name="event">Window Event</param>
event = event || window.event;
if (touchFlag && moveTouchFlag) {
//获取结束触摸事件对象
touchEnd = new EncapsulationTouch(event.changedTouches, event);
var xDistance = touchStart.touch1.x - touchEnd.touch1.x,
yDistance = touchStart.touch1.y - touchEnd.touch1.y;
if (baseHandle.end) {
//响应事件
setTimeout(function () {
baseHandle.end.call(this, touchStart, touchEnd, [xDistance, yDistance]);
}, 1);
}
var customEvent = that.customEvent;
if (customEvent) {
var touchEndEvent = customEvent.onTouchEnd;
if (touchEndEvent && typeof (touchEndEvent) == 'function') {
setTimeout(function () {
touchEndEvent.call(this, touchStart, touchEnd, [xDistance, yDistance]);
}, 1);
}
var slideEndEvent = customEvent.onSlideEnd;
if (slideEndEvent && typeof (slideEndEvent) == 'function') {
setTimeout(function () {
slideEndEvent.call(this, touchStart, touchEnd, [xDistance, yDistance]);
}, 1);
}
}
//还原Touch状态
touchFlag = false;
moveTouchFlag = false;
this.onclick = function () {
this.onclick = null;
return false;
};
}
};
var type = null;
if (isTouch()) {
type = EventType.touchType;
}
else if (isMSPointer()) {
type = EventType.MSPointerType;
}
else if (isPointer()) {
type = EventType.pointerType;
}
else {
type = EventType.mouseType;
}
if (type) {
bindEvent(target[0], type.start, startHandle);
bindEvent(target[0], type.move, moveHandle);
bindEvent(target[0], type.end, endHandle);
}
}
};
install();
//触摸开始
that.onTouchStart = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onTouchStart'] = fun;
}
return that;
};
//触摸滑动
that.onTouchMove = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onTouchMove'] = fun;
}
return that;
};
//触摸结束
that.onTouchEnd = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onTouchEnd'] = fun;
}
return that;
};
//向上滑动(返回参数touchStart, touchMove, yDistance)
that.onSlideUp = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onSlideUp'] = fun;
}
return that;
};
//向下滑动(返回参数touchStart, touchMove, yDistance)
that.onSlideDown = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onSlideDown'] = fun;
}
return that;
};
//向左滑动(返回参数touchStart, touchMove, xDistance)
that.onSlideLeft = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onSlideLeft'] = fun;
}
return that;
};
//向右滑动(返回参数touchStart, touchMove, xDistance)
that.onSlideRight = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onSlideRight'] = fun;
}
return that;
};
//滑动结束
that.onSlideEnd = function (fun) {
if (fun) {
that.customEvent = that.customEvent || {};
that.customEvent['onSlideEnd'] = fun;
}
return that;
};
};
});
/**
*
* Sliders 滑块切换效果
*
* version 1.0.0.0(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年7月25日09:33:24
*
* update log 2014年7月30日17:48:57
*
* remark 依赖于Thread和Touch模块
*
*/
Module.Create('Sliders', function () {
/// <summary>
/// 实现滚动效果函数对象(依赖于Thread和Touch模块)
/// </summary>
var that = this;
//移动端触摸滑动效果(依赖于Touch、Thread模块)
that.TouchSlider = function (options) {
/// <summary>
/// 移动端触摸滑动效果(依赖于Touch、Thread模块)
/// </summary>
/// <param name="options" type="JSON Object">函数对象所需参数对象集合</param>
var that = this;
//创建实体对象
var SliderModel = function (model) {
/// <summary>
/// 滑动效果实体对象
/// </summary>
/// <param name="model" type="JSON Object">实体对象</param>
var that = this;
//容器对象
that.container = $(model.container || document.body);
//滚动项每一项的宽度
that.itemWidth = model.itemWidth;
//一次滚动多少个项
that.switchCount = model.switchCount || 1;
//是否自动播放
that.isAutoPlay = model.isAutoPlay != undefined && model.isAutoPlay != null ? model.isAutoPlay : true;
//滚动时间间隔
that.timeout = model.timeout || 5000;
//是否无缝隙滚动
that.isSeamlessSwitch = model.isSeamlessSwitch != undefined && model.isSeamlessSwitch != null ? model.isSeamlessSwitch : true;
//滚动目标元素
that.switchTarget = model.switchTarget || '.J-target-slider';
//滚动目标元素Item
that.switchTargetItem = model.switchTargetItem || '.J-slider-item';
//滚动指示器
that.indicators = model.indicators || '.J-slider-indicators';
//指示器Item
that.indicatorsItem = model.indicatorsItem || '.ui-slider-indicator';
//当前项
that.currentIndicators = model.currentIndicators || 'ui-slider-indicator-current';
//自定义事件
that.customEvent = model.customEvent || new Object();
};
//实例化实体对象
var SliderModelInstance = new SliderModel(options || {});
//初始化操作
var install = function () {
var container = SliderModelInstance.container;
var switchTarget = container.find(SliderModelInstance.switchTarget),
switchTargetItem = container.find(SliderModelInstance.switchTargetItem),
indicators = container.find(SliderModelInstance.indicators),
indicatorsItem = container.find(SliderModelInstance.indicatorsItem);
var indicatorsWidth = indicatorsItem.length * 20;
indicators.css('width', indicatorsWidth + 'px').css('margin-left', -(indicatorsWidth / 2) + 'px');
//Item长度
var itemLength = switchTargetItem.length;
//Item宽度
var itemWidth = SliderModelInstance.itemWidth || switchTargetItem[0].offsetWidth;
//内容总宽度
var contentWidth = itemLength * itemWidth;
//设置内容宽度
switchTarget.css('position', 'absolute').css('width', (contentWidth) + 'px').css('float', 'left');
switchTargetItem.css('width', (itemWidth) + 'px').css('float', 'left');
if ($('#strQty').length) {
setTimeout(function () {
container.css('height', container.find('.ui-slider-repeater').eq(0).height() + 'px');
}, 500);
}
//复制一个滚动元素作为无缝切换效果
var cloneSwitchTarget = switchTarget.clone().css('margin-left', -contentWidth + 'px').attr('data-left', -contentWidth);
switchTarget.before(cloneSwitchTarget);
//自定义事件
var customEvent = SliderModelInstance.customEvent;
//点击事件
container.click(function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
var $target = $(target);
//响应自定义事件-点击事件
if (customEvent) {
var clickEvent = customEvent.onClick;
if (clickEvent && typeof (clickEvent) == 'function') {
//返回当前点击目标元素对象
clickEvent.call(this, $target);
}
}
});
//滑动事件
var TouchModule = Module.Use('Touch');
var startLeft, cloneStartLeft;
TouchModule.TouchSlide({
target: container,
handle: {
start: function (startTouch) {
startLeft = parseInt(switchTarget.attr('data-left') || 0);
cloneStartLeft = parseInt(cloneSwitchTarget.attr('data-left') || 0);
switchTarget.removeClass('transition');
cloneSwitchTarget.removeClass('transition');
SliderModelInstance.Thread.stop();
},
move: function (startTouch, moveTouch) {
var x = moveTouch.touch1.x - startTouch.touch1.x;
//设置
switchTarget.css('margin-left', (startLeft + x) + 'px');
cloneSwitchTarget.css('margin-left', (cloneStartLeft + x) + 'px');
},
end: function (startTouch, endTouch) {
switchTarget.addClass('transition');
cloneSwitchTarget.addClass('transition');
var x = endTouch.touch1.x - startTouch.touch1.x;
if (Math.abs(x) >= itemWidth / 3) {
//如果滑动距离大于屏幕宽的三分之一,就移动到下一屏内容
if (x < 0) {
//向左
roll('left');
}
else {
//向右
roll('right');
}
}
else {
//还原
switchTarget.css('margin-left', (startLeft) + 'px');
cloneSwitchTarget.css('margin-left', (cloneStartLeft) + 'px');
}
SliderModelInstance.Thread.start();
}
}
});
//滚动
var item = 0;
var roll = function (direction) {
//滚动方向
var sliderDirection = direction || (container.attr('data-sliderDirection') || 'left');
//目标元素当前Left值
var marginLeft = parseInt(switchTarget.attr('data-left') || 0),
//克隆元素Left值
cloneMarginLeft = parseInt(cloneSwitchTarget.attr('data-left') || 0);
//滚动距离
var scrollLeft = itemWidth * SliderModelInstance.switchCount;
if (sliderDirection == 'left') {
//向左滚动
var mLeft = marginLeft - scrollLeft,
cloneMLeft = cloneMarginLeft - scrollLeft;
//switchTarget.css('margin-left', (mLeft) + 'px').attr('data-left', mLeft);
//cloneSwitchTarget.css('margin-left', (cloneMLeft) + 'px').attr('data-left', cloneMLeft);
item++;
if (item >= itemLength) {
item = 0;
}
indicators.find('.' + SliderModelInstance.currentIndicators).removeClass(SliderModelInstance.currentIndicators);
indicatorsItem.eq(item).addClass(SliderModelInstance.currentIndicators);
//console.log(mLeft + '<--->' + itemWidth + '<--->' + (mLeft - itemWidth) + '<--->' + (-contentWidth));
if (mLeft - itemWidth == -contentWidth) {
cloneSwitchTarget.css('margin-left', (itemWidth) + 'px').attr('data-left', itemWidth);
}
else {
cloneSwitchTarget.css('margin-left', (cloneMLeft) + 'px').attr('data-left', cloneMLeft);
}
if (cloneMLeft - itemWidth == -contentWidth) {
switchTarget.css('margin-left', (itemWidth) + 'px').attr('data-left', itemWidth);
}
else {
switchTarget.css('margin-left', (mLeft) + 'px').attr('data-left', mLeft);
}
container.attr('data-sliderDirection', 'left');
//响应自定义事件-向左滚动事件
if (customEvent) {
var sliderLeftEvent = customEvent.onSliderLeft;
if (sliderLeftEvent && typeof (sliderLeftEvent) == 'function') {
//返回当前滚动元素对象
sliderLeftEvent.call(this, switchTarget);
}
}
}
else if (sliderDirection == 'right') {
//向右滚动
var mLeft = marginLeft + scrollLeft,
cloneMLeft = cloneMarginLeft + scrollLeft;
switchTarget.css('margin-left', (mLeft) + 'px').attr('data-left', mLeft);
cloneSwitchTarget.css('margin-left', (cloneMLeft) + 'px').attr('data-left', cloneMLeft);
item--;
if (item < 0) {
item = itemLength - 1;
}
indicators.find('.' + SliderModelInstance.currentIndicators).removeClass(SliderModelInstance.currentIndicators);
indicatorsItem.eq(item).addClass(SliderModelInstance.currentIndicators);
if (mLeft == 0) {
cloneSwitchTarget.css('margin-left', (-contentWidth) + 'px').attr('data-left', -contentWidth);
}
if (cloneMLeft == 0) {
switchTarget.css('margin-left', (-contentWidth) + 'px').attr('data-left', -contentWidth);
}
container.attr('data-sliderDirection', 'right');
//响应自定义事件-向右滚动事件
if (customEvent) {
var sliderRightEvent = customEvent.onSliderRight;
if (sliderRightEvent && typeof (sliderRightEvent) == 'function') {
//返回当前滚动元素对象
sliderRightEvent.call(this, switchTarget);
}
}
}
//响应自定义事件-滚动事件
if (customEvent) {
var sliderEvent = customEvent.onSlider;
if (sliderEvent && typeof (sliderEvent) == 'function') {
//返回当前滚动元素对象
sliderEvent.call(this, switchTarget);
}
}
};
//是否自动切换
if (SliderModelInstance.isAutoPlay) {
//引入时间线程对象
var sliderThread = Module.Use('Thread');
//自动切换
SliderModelInstance.Thread = new sliderThread.Thread(roll, SliderModelInstance.timeout);
if (indicatorsItem.length > 1) {
SliderModelInstance.Thread.start();
}
}
};
install();
that.onClick = function (fun) {
if (fun) {
SliderModelInstance.customEvent = SliderModelInstance.customEvent || {};
SliderModelInstance.customEvent['onClick'] = fun;
}
return that;
};
that.onSlider = function (fun) {
if (fun) {
SliderModelInstance.customEvent = SliderModelInstance.customEvent || {};
SliderModelInstance.customEvent['onSlider'] = fun;
}
return that;
};
that.onSliderLeft = function (fun) {
if (fun) {
SliderModelInstance.customEvent = SliderModelInstance.customEvent || {};
SliderModelInstance.customEvent['onSliderLeft'] = fun;
}
return that;
};
that.onSliderRight = function (fun) {
if (fun) {
SliderModelInstance.customEvent = SliderModelInstance.customEvent || {};
SliderModelInstance.customEvent['onSliderRight'] = fun;
}
return that;
};
};
});
/**
*
* 简单的表单验证
*
* version 1.2.5.2(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年8月10日15:55:27
*
* update log 2014年11月29日10:12:27
*
*/
Module.Create('Validation', function () {
/// <summary>
/// 选项卡切换
/// </summary>
var that = this;
that.FormValidation = function (options) {
var that = this;
//表单验证实体类
var FormValidationModel = function (model) {
var that = this;
//表单
that.form = $(model.form || '.J-form-validation');
//自定义验证类型
that.verify = model.verify;
//是否响应事件
that.isInteraction = isFalse(model.isInteraction) ? false : true;
//测试验证时执行一次自定义事件
that.executeOnceCustomEvent = model.executeOnceCustomEvent || false;
//各中状态下的className
that.status = model.status || {
//验证失败
failure: 'ui-form-item-failure',
//验证错误
error: 'ui-form-item-error',
//成功
success: 'ui-form-item-success',
//警告
warning: 'ui-form-item-warning',
//获取焦点
focus: 'ui-form-item-focus'
};
//元素自定义键
that.keys = model.keys || {
//为空提示
dataRequiredTip: 'data-required-tip',
//警告提示
dataWarningTip: 'data-required-tip',
//错误消息
dataErrorTip: 'data-error-tip',
//成功消息
dataSuccessTip: 'data-success-tip',
//关联元素
dataToggle: 'data-toggle'
};
};
var FormValidationModelInstance = new FormValidationModel(options || {});
//基本配置实体类
var ConfigModel = function () {
var that = this;
//被验证目标元素
that.verifyTarget = 'J-verify';
//必填、必选项
that.required = 'J-required';
//一般的验证在验证通过后就不再执行验证表达式在被验证元素上设置该属性为true时不管该元素的验证是否通过都会继续执行验证表达式
that.continuousKey = 'data-continuous';
//异步验证键
that.asyncKey = 'data-async';
//test中的异步验证回调操作键
that.asyncCallBackKey = 'data-asyncCallBack';
//(异步)验证状态键
that.asyncStatusKey = 'data-asyncStatus';
//(异步)验证状态[状态: 1.基础验证未通过、2.基础验证通过、3.异步验证未通过、4异步验证中、5.异步验证通过]
that.asyncStatus = { baseNotPass: 1, basePass: 2, asyncNotPass: 3, asyncVerifying: 4, asyncPass: 5 };
};
var ConfigModelInstance = new ConfigModel();
//验证类型实体类
var VerifyTypeModel = function () {
var that = this;
that['J-v000'] = { regular: /^[0-9a-zA-Z_.\-]{1,}$/, remark: '只能为数字,字母,下划线,中划线,点' };
that['J-v001'] = { regular: /^[\u4E00-\u9FA5\uF900-\uFA2D0-9a-zA-Z\-\_\(\)\\]{1,}$/, remark: '只能为中文,括号,数字或字母,中划线,下划线' }
that['J-v002'] = { regular: /^[\u4E00-\u9FA5\uF900-\uFA2Da-zA-Z\-\_]{1,}$/, remark: '只能为中文,字母,中划线,下划线' };
that['J-v003'] = { regular: /^[\u4E00-\uFA29]*$/, remark: '只能为中文' };
that['J-v004'] = { regular: /^[\uFF00-\uFFFF\u4E00-\u9FA5\uF900-\uFA2D\u20140-9a-zA-Z.@\-_]{1,}$/, remark: '只能为中文,数字或字母,中划线,下划线,点,@' };
that['J-float2'] = { regular: /^(-?\d+)(\.\d{1,2})?$/, remark: '请输入浮点数(两位有效数字)' };
that['J-alphaNumeric'] = { regular: /^[A-Za-z0-9]+$/, remark: '只能为字母和数字' };
that['J-letters'] = { regular: /^[A-Za-z]+$/, remark: '只能为字母' };
that['J-int'] = { regular: /^[1-9]*[1-9][0-9]*$/, remark: '请输入正整数' };
that['J-num'] = { regular: /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/, remark: '请输入数字' };
that['J-email'] = { regular: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/, remark: '请输入正确的邮件(如:xxx@163.com)' };
that['J-tel'] = { regular: /^(\d{3}-|\d{4}-)?(\d{8}|\d{7})?$/, remark: '请输入正确的座机号码(如:68888888)' };
that['J-phone'] = { regular: /^1[3-9]{1}[0-9]{9}$/, remark: '请输入正确的手机号码(如:13888888888)' };
that['J-url'] = { regular: /^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/, remark: '请输入正确的地址' };
that['J-postCode'] = { regular: /^[1-9][0-9]{5}$/, remark: '请输入正确的邮编(如:400000)' };
that['J-longitude'] = { regular: /^-?(?:(?:180(?:\.0{1,5})?)|(?:(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d{1,5})?))$/, remark: '经度(-180.00000~180.00000)' };
that['J-latitude'] = { regular: /^-?(?:90(?:\.0{1,5})?|(?:[1-8]?\d(?:\.\d{1,5})?))$/, remark: '纬度(-90.00000~90.00000)' };
that['J-idCard'] = { regular: /^(\d{11}|\d{14})\d{3}?(\d|X|x)$/, remark: '请输入正确的身份证号码' };
that['J-qq'] = { regular: /^[1-9]*[1-9][0-9]*$/, remark: '请输入正确的QQ' };
that['J-notNullByFloat1'] = { regular: /^[0-9]+(\.[0-9]{1})?$/, remark: '非空且保留一位小数' };
that['J-notNullByFloat2'] = { regular: /^\\d{1,8}\\.{0,1}(\\d{1,2})?$/, remark: '非空且保留两位小数' };
that['J-pure-digital'] = function (value) {
var result = { status: true, message: 'OK', type: 'success' };
if (isNumber(value)) {
result = { status: false, message: '不能是纯数字', type: 'failure', level: 1 };
}
return result;
};
that['J-phone-email'] = function (value) {
var result = { status: false, message: null, type: 'failure' };
if (isNumber(value)) {
var status = new RegExp(/^1[3-9]{1}[0-9]{9}$/).test(value);
if (status) {
result = { status: true, message: '成功!', type: 'success', flag: 'phone' };
}
else {
result = { status: false, message: '手机号码格式不正确', type: 'failure' };
}
}
else {
var status = new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(value);
if (status) {
result = { status: true, message: '成功!', type: 'success', flag: 'email' };
}
else {
result = { status: false, message: '邮箱格式不正确', type: 'failure' };
}
}
return result;
};
var verifyType = FormValidationModelInstance.verify;
if (verifyType) {
for (var key in verifyType) {
that[key] = verifyType[key];
}
}
};
var VerifyTypeModelInstance = new VerifyTypeModel();
//语言包实体类
var LangModel = function () {
var that = this;
//必选提示
that.L001 = '必选';
//必填提示
that.L002 = '必填';
};
var LangModelInstance = new LangModel();
//获取表单中的数据(以元素的Name作为键如果没有Name属性则以标签名称递增方式作为键)
var getFormData = function (form) {
/// <summary>
/// 获取表单中的数据(以元素的Name作为键如果没有Name属性则以标签名称递增方式作为键)
/// </summary>
/// <param name="form" type="Element">需要获取数据的Form表单元素(非必填,默认为当前被验证表单)</param>
/// <returns type="Object" />当前获取到的数据集合
var i, elementLength, inputs, selects, textareas, element, value, result, group, key, type, check;
form = form || FormValidationModelInstance.form;
//获取表单下所有input
inputs = form.find('input');
//获取表单下所有select
selects = form.find('select');
//获取表单下所有textarea
textareas = form.find('textarea');
if (inputs.length > 0 || selects.length > 0 || textareas.length > 0) {
//result.当前表单下的数据JSON对象, group.用于判断同一个分组的radio或checkbox
result = {}, group = "";
//遍历inputs
elementLength = inputs.length;
for (i = 0; i < elementLength; i++) {
element = inputs[i];
//获取value并去除首尾的空格
value = encodeURIComponent(element.value.replace(/(^\s*)/g, '').replace(/(\s*$)/g, ''));
//获取当前元素id用作key
key = element.getAttribute("name");
//如果没有id就为该标签名加i
key = key ? key : element.nodeName + i;
//获取标签的type用于判断标签类型
type = element.getAttribute("type");
if (type == "radio" || type == "checkbox") {
//获取name该key用name代替
key = element.getAttribute("name");
group = key != group ? key : group;
if (key == group) {
check = element.checked;
if (check) { result[key] = result[key] ? result[key] + ',' + value : value; }
}
}
else if (type == "text" || type == "password" || type == "hidden") { result[key] = value; }
}
//遍历selects
elementLength = selects.length;
for (i = 0; i < elementLength; i++) {
element = selects[i];
key = element.getAttribute('name');
key = key ? key : element.nodeName + i;
value = element.value.replace(/(^\s*)/g, '').replace(/(\s*$)/g, '');
result[key] = value;
}
//遍历textareas
elementLength = textareas.length;
for (i = 0; i < elementLength; i++) {
element = textareas[i];
key = element.getAttribute('name');
key = key ? key : element.nodeName + i;
value = element.value.replace(/(^\s*)/g, '').replace(/(\s*$)/g, '');
result[key] = value;
}
}
return result;
};
//异步验证
var asyncVerify = function (options) {
var asyncVerifyModel = function (model) {
var that = this;
//被验证元素
that.target = model.target;
//请求路径
that.url = model.url;
//提交数据
that.data = model.data;
//请求开始
that.requestBegin = model.requestBegin;
//请求失败
that.requestError = model.requestError;
//请求成功
that.callBack = model.callBack;
};
var asyncVerifyModelInstance = new asyncVerifyModel(options || {});
if (typeof (asyncVerifyModelInstance.target) == 'string') {
asyncVerifyModelInstance.target = FormValidationModelInstance.form.find(asyncVerifyModelInstance.target);
}
//获取异步验证方法的键
var asyncKey = asyncVerifyModelInstance.target.attr(ConfigModelInstance.asyncKey);
if (!asyncKey) {
asyncKey = Module.Guid(ConfigModelInstance.asyncKey.replace('-', '').toLocaleUpperCase());
asyncVerifyModelInstance.target.attr(ConfigModelInstance.asyncKey, asyncKey);
}
FormValidationModelInstance.asyncHandle = FormValidationModelInstance.asyncHandle || {};
FormValidationModelInstance.asyncHandle[asyncKey] = asyncVerifyModelInstance;
};
//单个元素验证
var regularVerify = function (target) {
/// <summary>
/// 对单个元素验证
/// </summary>
/// <param name="target" type="Element">被验证的DOM元素对象</param>
/// <returns type="Boolean" />验证是否通过
/// <remarks/>执行步骤(第一、二、三、四步)最好不要调换
var result = { status: true, message: 'OK', type: 'success' };
var form = FormValidationModelInstance.form,
keys = FormValidationModelInstance.keys, tempTarget;
if (target) {
//获取自定义消息内容
var requiredMessage = $(target).attr(keys.dataRequiredTip),
//错误消息
errorMessage = $(target).attr(keys.dataErrorTip),
//警告消息
warningMessage = $(target).attr(keys.dataWarningTip),
//成功消息
successMessage = $(target).attr(keys.dataSuccessTip);
var value = target.value,
name = target.name,
type = target.type,
checkBox;
if (type == 'radio' || type == 'checkbox') {
//获取同一组的元素
checkBox = form.find('input[name=' + name + ']');
target = checkBox[0];
}
//第一步,非空验证(必填或必选)
var required = $(target).hasClass(ConfigModelInstance.required);
if (required) {
if (type == 'radio' || type == 'checkbox') {
if (name) {
var i = 0, length = checkBox.length, flag = 0;
//循环获取有多少个被选中
for (; i < length; i++) {
if (checkBox[i].checked) {
flag++;
}
}
if (flag <= 0) {
result.status = false;
result.message = $(target).attr(keys.dataRequiredTip) || LangModelInstance.L001;
result.type = 'warning';
//##错误提示操作##//
return result;
}
else {
//如果有选中的项,再验证选中项个数限制
var minLength = target.getAttribute('minlength'),
maxLength = target.getAttribute('maxlength');
//长度判断
if (minLength) {
minLength = parseInt(minLength);
if (flag < minLength) {
result.status = false;
result.message = '至少需要选择#MIN#项'.replace('#MIN#', minLength);
result.type = 'warning';
return result;
}
}
if (maxLength) {
maxLength = parseInt(maxLength);
if (flag > maxLength) {
result.status = false;
result.message = '最多只能选择#MAX#项'.replace('#MAX#', maxLength);
result.type = 'warning';
return result;
}
}
}
}
}
else if (!value) {
var nodeName = target.nodeName.toLocaleLowerCase();
result.status = false;
result.message = nodeName === 'input' || nodeName === 'textarea' ? $(target).attr(keys.dataRequiredTip) || LangModelInstance.L002 : $(target).attr(keys.dataRequiredTip) || LangModelInstance.L001;
result.type = 'warning';
return result;
}
}
if (value) {
//第三步,验证长度
var valueLength = value.length;
//获取关联
var equalTo = target[keys.dataToggle];
equalTo = equalTo ? equalTo : target.getAttribute(keys.dataToggle);
//是否存在异步验证
var asyncKeys = $(target).attr(ConfigModelInstance.asyncKey);
//最小长度
var minLength = target.minlength;
minLength = parseInt(minLength ? minLength : target.getAttribute('minlength'));
var minByte = $(target).attr('minByte');
if (minLength) {
if (valueLength < minLength) {
result.status = false;
if (equalTo || asyncKeys) {
//如果有关联(消息应该是为关联的错误消息)
result.message = '至少需要#MINLENGTH#个字符'.replace('#MINLENGTH#', minLength);
}
else {
result.message = errorMessage || '至少需要#MINLENGTH#个字符'.replace('#MINLENGTH#', minLength);
}
result.type = 'failure';
return result;
}
}
//字节判断
if (minByte) {
minByte = parseInt(minByte);
var charByte = value.getCharByte();
if (charByte < minByte) {
result.status = false;
if (equalTo || asyncKeys) {
//如果有关联(消息应该是为关联的错误消息)
result.message = '至少需要#MINLENGTH#个字节'.replace('#MINLENGTH#', minByte);
}
else {
result.message = errorMessage || '至少需要#MINLENGTH#个字节'.replace('#MINLENGTH#', minByte);
}
result.type = 'failure';
return result;
}
}
//最大长度
var maxLength = target.maxlength;
maxLength = parseInt(maxLength ? maxLength : target.getAttribute('maxlength'));
var maxByte = $(target).attr('maxByte');
if (maxLength) {
if (valueLength > maxLength) {
result.status = false;
if (equalTo) {
//如果有关联(消息应该是为关联的错误消息)
result.message = '最多只需#MINLENGTH#个字符'.replace('#MINLENGTH#', maxLength);
}
else {
result.message = errorMessage || '最多只需#MINLENGTH#个字符'.replace('#MINLENGTH#', maxLength);
}
result.type = 'failure';
return result;
}
}
//字节判断
if (maxByte) {
maxByte = parseInt(maxByte);
var charByte = value.getCharByte();
if (charByte > maxByte) {
result.status = false;
if (equalTo || asyncKeys) {
//如果有关联(消息应该是为关联的错误消息)
result.message = '最多只需#MINLENGTH#个字节'.replace('#MINLENGTH#', maxByte);
}
else {
result.message = errorMessage || '最多只需#MINLENGTH#个字节'.replace('#MINLENGTH#', maxByte);
}
result.type = 'failure';
return result;
}
}
//第二步,格式验证
var verifyType = VerifyTypeModelInstance;
for (var key in verifyType) {
if ($(target).hasClass(key)) {
result = matchVerifyType(value, key);
if (!result.status) {
var dataErrorTip = $(target).attr(keys.dataErrorTip);
if (dataErrorTip && !result.level) {
result.message = dataErrorTip;
}
return result;
}
}
}
//第四步(最后一步),关联验证
if (equalTo) {
//找到其关联的元素
var equalElement = form.find(equalTo)[0];
if (equalElement) {
//获取关联元素的value
var equalValue = equalElement.value;
equalValue = equalValue ? equalValue : equalElement.innerHTML;
//获取key该key值为'>'、'<'、'=='、'>='等用于验证两者间关系,默认为'=='
var key = target.getAttribute('key');
key = key ? key : '==';
var compare;
switch (key) {
case '>': compare = '大于'; break;
case '<': compare = '小于'; break;
case '>=': compare = '大于等于'; break;
case '<=': compare = '小于等于'; break;
default: compare = '等于'; break;
}
if (key == '==') {
if (value != equalValue) {
result.status = false;
result.message = errorMessage || '与关联值不一致';
result.type = 'failure';
return result;
}
}
else {
var flag = false;
eval('if(parseInt(value) ' + key + ' parseInt(equalValue)){ flag = true; }');
if (!flag) {
result.status = false;
result.message = errorMessage || "值必须#KEY##EQVAL#".replace('#KEY#', compare).replace('#EQVAL#', equalValue);
result.type = 'failure';
return result;
}
}
}
}
}
}
return result;
};
//匹配验证类型
var matchVerifyType = function (regValue, regType) {
/// <summary>
/// 正则验证
/// </summary>
/// <param name="regValue" type="String">需要验证的内容</param>
/// <param name="regType" type="String">验证的类型</param>
/// <returns type="JSON Object" />返回验证结果{status: 状态, message: 消息内容, type: 消息类型}
regType = regType ? regType : 'J-alphaNumeric';
var verifyType = VerifyTypeModelInstance[regType];
var result = { status: true, message: 'OK', type: 'success' };
if (typeof (verifyType) == 'function') {
result = verifyType(regValue);
}
else {
if (regType == 'J-telPhone') {
result = matchVerifyType(regValue, 'J-tel');
if (!result.status) {
result = matchVerifyType(regValue, 'J-phone');
}
}
else if (regType == 'J-alphaNumerics') {
regValue = regValue.substring(0, 1);
if (!isNaN(regValue)) {
result.status = false;
result.type = 'failure';
result.message = verifyType['remark'];
}
}
else {
result.status = new RegExp(verifyType['regular']).test(regValue);
result.type = result.status ? 'success' : 'failure';
result.message = verifyType['remark'];
}
}
return result;
};
//验证
var verify = function (target, callBack) {
target = $(target);
//响应验证(前)事件
var customEvent = FormValidationModelInstance.customEvent;
var isInteraction = FormValidationModelInstance.isInteraction;
if (customEvent && isInteraction) {
var verifyEvent = customEvent.onVerify;
if (verifyEvent) {
verifyEvent.call(target);
}
}
var asyncStatus = ConfigModelInstance.asyncStatus,
asyncStatusKey = ConfigModelInstance.asyncStatusKey;
var result = regularVerify(target[0]);
if (result.status) {
target.attr(asyncStatusKey, asyncStatus.basePass);
//做异步验证处理
var asyncKey = target.attr(ConfigModelInstance.asyncKey), asyncFlag = true;
if (asyncKey) {
var asyncHandle = FormValidationModelInstance.asyncHandle[asyncKey];
if (asyncHandle) {
var postData = asyncHandle.data || {};
var targetName = target.attr('name') || asyncKey;
postData[targetName] = target.val();
target.attr(asyncStatusKey, asyncStatus.asyncVerifying);
$.ajax({
url: asyncHandle.url,
data: postData,
type: "POST",
beforeSend: function () {
if (asyncHandle.requestBegin) {
asyncHandle.requestBegin(target);
}
var customEvent = FormValidationModelInstance.customEvent;
if (customEvent) {
var asyncVerifyBeginEvent = customEvent.onAsyncVerifyBegin;
if (asyncVerifyBeginEvent) {
asyncVerifyBeginEvent.call(target);
}
}
},
error: function (responseText, response) {
target.attr(asyncStatusKey, asyncStatus.asyncNotPass);
result.status = false;
result.type = 'error';
result.message = target.attr(FormValidationModelInstance.keys.dataErrorTip) || 'Error';
if (asyncHandle.requestError) {
asyncHandle.requestError(responseText, response, target, result);
}
if (callBack) {
callBack.call(target, result);
}
//获取异步验证CallBack键
var asyncCallBackKey = target.attr(ConfigModelInstance.asyncCallBackKey);
if (asyncCallBackKey) {
var asyncCallBackHandle = FormValidationModelInstance.asyncCallBack[asyncCallBackKey];
if (asyncCallBackHandle) {
asyncCallBackHandle.call(target, result);
}
}
//验证失败
if (customEvent && isInteraction) {
//响应验证失败事件
var verifyFailureEvent = customEvent.onVerifyFailure;
if (verifyFailureEvent) {
verifyFailureEvent.call(target, result);
}
//结束当前验证
//响应验证结束事件
var verifyEndEvent = customEvent.onVerifyEnd;
if (verifyEndEvent) {
verifyEndEvent.call(target, result);
}
}
},
success: function (responseText, response) {
if (isTrue(responseText) || isFalse(responseText)) {
if (isTrue(responseText)) {
//异步验证通过状态设置
target.attr(asyncStatusKey, asyncStatus.asyncPass);
result.status = true;
result.type = 'success';
result.message = target.attr(FormValidationModelInstance.keys.dataSuccessTip) || 'Ok';
if (customEvent && isInteraction) {
var verifySuccessEvent = customEvent.onVerifySuccess;
if (verifySuccessEvent) {
verifySuccessEvent.call(target, result);
}
}
}
else {
//异步验证未通过状态设置
target.attr(asyncStatusKey, asyncStatus.asyncNotPass);
result.status = false;
result.type = 'failure';
result.message = 'Failure';
if (customEvent && isInteraction) {
var verifyFailureEvent = customEvent.onVerifyFailure;
if (verifyFailureEvent) {
verifyFailureEvent.call(target, result);
}
}
}
}
else {
if (value != responseText) {
//异步验证通过状态设置
target.attr(asyncStatusKey, asyncStatus.asyncPass);
result.status = true;
result.type = 'success';
result.message = 'ok';
if (customEvent && isInteraction) {
var verifySuccessEvent = customEvent.onVerifySuccess;
if (verifySuccessEvent) {
verifySuccessEvent.call(target, result);
}
}
}
else {
//异步验证未通过状态设置
target.attr(asyncStatusKey, asyncStatus.asyncNotPass);
result.status = false;
result.type = 'failure';
result.message = 'Failure';
if (customEvent && isInteraction) {
var verifyFailureEvent = customEvent.onVerifyFailure;
if (verifyFailureEvent) {
verifyFailureEvent.call(target, result);
}
}
}
}
if (asyncHandle.callBack) {
asyncHandle.callBack(responseText, response, target, result);
}
if (callBack) {
callBack.call(target, result);
}
//获取异步验证CallBack键
var asyncCallBackKey = target.attr(ConfigModelInstance.asyncCallBackKey);
if (asyncCallBackKey) {
var asyncCallBackHandle = FormValidationModelInstance.asyncCallBack[asyncCallBackKey];
if (asyncCallBackHandle) {
asyncCallBackHandle.call(target, result);
}
}
//结束当前验证
if (customEvent && isInteraction) {
//响应验证结束事件
var verifyEndEvent = customEvent.onVerifyEnd;
if (verifyEndEvent) {
verifyEndEvent.call(target, result);
}
}
}
});
}
else {
asyncFlag = false;
}
}
else {
asyncFlag = false;
}
if (!asyncFlag) {
target.attr(asyncStatusKey, asyncStatus.basePass);
if (callBack) {
callBack.call(target, result);
}
if (customEvent && isInteraction) {
//响应验证成功事件
var verifySuccessEvent = customEvent.onVerifySuccess;
if (verifySuccessEvent) {
verifySuccessEvent.call(target, result);
}
//结束当前验证
//响应验证结束事件
var verifyEndEvent = customEvent.onVerifyEnd;
if (verifyEndEvent) {
verifyEndEvent.call(target, result);
}
}
}
}
else {
target.attr(asyncStatusKey, asyncStatus.baseNotPass);
//验证失败
if (callBack) {
callBack.call(target, result);
}
if (customEvent && isInteraction) {
//响应验证失败事件
var verifyFailureEvent = customEvent.onVerifyFailure;
if (verifyFailureEvent) {
verifyFailureEvent.call(target, result);
}
//结束当前验证
//响应验证结束事件
var verifyEndEvent = customEvent.onVerifyEnd;
if (verifyEndEvent) {
verifyEndEvent.call(target, result);
}
}
}
};
//验证测试
var test = function (callBack) {
var verifyTargets = FormValidationModelInstance.form.find('.' + ConfigModelInstance.verifyTarget);
var i = 0, length = verifyTargets.length, target, targetAsyncStatus, targetContinuousFlag, count = 0, tempResult = [],
asyncStatusKey = ConfigModelInstance.asyncStatusKey,
asyncStatus = ConfigModelInstance.asyncStatus,
continuousFlag = ConfigModelInstance.continuousKey,
executeOnceCustomEvent = FormValidationModelInstance.executeOnceCustomEvent,
isInteraction = FormValidationModelInstance.isInteraction,
executeCount = 0;
//执行一次自定义事件
//FormValidationModelInstance.executeOnceCustomEvent = true;
var callBackHandle = function (result) {
if (result.status) {
count++;
if (count == length) {
if (callBack) {
callBack.call(this, getFormData());
}
//恢复
//FormValidationModelInstance.executeOnceCustomEvent = false;
}
}
else {
//遇到错误,就清空线程停止下面的验证
window.clearInterval(IntervalThread);
IntervalThread = null;
if (i == length) {
if (executeOnceCustomEvent) {
//还原
FormValidationModelInstance.isInteraction = isInteraction;
}
if (count < length) {
//响应测试失败事件
var customEvent = FormValidationModelInstance.customEvent;
if (customEvent) {
var testFailure = customEvent.onTestFailure;
if (testFailure) {
testFailure.call(this);
}
}
}
}
}
};
var IntervalThread = window.setInterval(function () {
if (!length) {
if (callBack) {
callBack.call(this, getFormData());
}
window.clearInterval(IntervalThread);
IntervalThread = null;
}
target = verifyTargets.eq(i);
i++;
targetAsyncStatus = target.attr(asyncStatusKey);
targetContinuousFlag = target.attr(continuousFlag);
if (targetAsyncStatus && targetContinuousFlag != 'true') {
if (targetAsyncStatus == asyncStatus.basePass || targetAsyncStatus == asyncStatus.asyncPass) {
var toggle = FormValidationModelInstance.keys.dataToggle;
var dataToggle = target.attr(toggle);
if (dataToggle) {
verify(target, callBackHandle);
}
else {
//验证为通过状态count++
callBackHandle({ status: true });
}
}
else if (targetAsyncStatus == asyncStatus.asyncVerifying) {
//正在验证中状态
//获取异步验证CallBack键
var asyncCallBackKey = target.attr(ConfigModelInstance.asyncCallBackKey);
if (!asyncCallBackKey) {
asyncCallBackKey = Module.Guid(ConfigModelInstance.asyncCallBackKey.replace('-', '').toLocaleUpperCase());
target.attr(ConfigModelInstance.asyncCallBackKey, asyncCallBackKey);
}
FormValidationModelInstance.asyncCallBack = FormValidationModelInstance.asyncCallBack || {};
FormValidationModelInstance.asyncCallBack[asyncCallBackKey] = callBackHandle;
}
else {
if (executeOnceCustomEvent) {
if (executeCount > 0) {
FormValidationModelInstance.isInteraction = false;
}
verify(target, callBackHandle);
executeCount++;
}
else {
verify(target, callBackHandle);
}
}
}
else {
if (executeOnceCustomEvent && executeCount > 0) {
FormValidationModelInstance.isInteraction = false;
}
verify(target, callBackHandle);
executeCount++;
}
if (i == length) {
window.clearInterval(IntervalThread);
IntervalThread = null;
}
}, 10);
};
that.addVerifyType = function (types) {
/// <summary>
/// 自定义验证类型
/// </summary>
/// <param name="type" type="Object">验证类型集合</param>
if (types) {
for (var key in types) {
VerifyTypeModelInstance[key] = types[key];
}
}
return that;
};
that.customVerify = function (target, type) {
/// <summary>
/// 自定义元素验证
/// </summary>
/// <param name="target" type="Element">被验证元素</param>
/// <param name="type" type="String">验证类型</param>
var result = null;
var value = $(target).val();
var verifyType = VerifyTypeModelInstance[type];
if (verifyType) {
if (isFunction(verifyType)) {
result = verifyType(value);
}
else {
var message = null;
if (isJSON(verifyType)) {
message = verifyType.remark;
verifyType = verifyType.regular;
}
result = { status: false, message: null, type: 'failure' };
var status = new RegExp(verifyType).test(value);
if (status) {
result = { status: true, message: '成功!', type: 'success' };
}
else {
result = { status: false, message: message || $(target).attr(FormValidationModelInstance.keys.dataErrorTip), type: 'failure' };
}
}
}
return that;
};
//验证被触发前事件
that.onVerifyTriggerBefore = function (fun) {
/// <summary>
/// 验证被触发前事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onVerifyTriggerBefore'] = fun;
}
return that;
};
//验证事件
that.onVerify = function (fun) {
/// <summary>
/// 验证事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onVerify'] = fun;
}
return that;
};
//验证结束事件
that.onVerifyEnd = function (fun) {
/// <summary>
/// 验证结束事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onVerifyEnd'] = fun;
}
return that;
};
//异步验证开始事件
that.onAsyncVerifyBegin = function (fun) {
/// <summary>
/// 异步验证开始事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onAsyncVerifyBegin'] = fun;
}
return that;
};
//验证成功事件
that.onVerifySuccess = function (fun) {
/// <summary>
/// 验证成功事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onVerifySuccess'] = fun;
}
return that;
};
//验证失败事件
that.onVerifyFailure = function (fun) {
/// <summary>
/// 验证失败事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onVerifyFailure'] = fun;
}
return that;
};
//表单验证测试失败事件
that.onTestFailure = function (fun) {
/// <summary>
/// 验证测试失败事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
if (fun) {
FormValidationModelInstance.customEvent = FormValidationModelInstance.customEvent || {};
FormValidationModelInstance.customEvent['onTestFailure'] = fun;
}
return that;
};
//表单所有验证元素测试事件(成功)
that.onFormTest = function (fun) {
/// <summary>
/// 表单所有验证元素测试事件
/// </summary>
/// <param name="fun" type="Function">事件函数</param>
test(fun);
return that;
};
//获取表单中的数据(以元素的Name作为键如果没有Name属性则以标签名称递增方式作为键)
that.getFormData = getFormData;
//给元素添加异步验证
that.asyncVerify = asyncVerify;
//设置自定义事件是否响应
that.interaction = function (flag) {
/// <summary>
/// 设置自定义事件是否响应
/// </summary>
/// <param name="flag" type="Boolean">true.响应(默认) false.不响应</param>
if (isFalse(flag)) {
flag = false;
}
else {
flag = true;
}
FormValidationModelInstance.isInteraction = flag;
return that;
};
var install = function () {
var form = FormValidationModelInstance.form;
form.click(function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
var $target = $(target);
var nodeName = target.nodeName.toLocaleLowerCase();
if (nodeName == 'input' || nodeName == 'select' || nodeName == 'textarea') {
if ($target.hasClass(ConfigModelInstance.verifyTarget)) {
//target.focus();
//执行验证
//verify(target);
//响应验证事件
var customEvent = FormValidationModelInstance.customEvent;
if (customEvent && FormValidationModelInstance.isInteraction) {
var verifyTriggerBeforeEvent = customEvent.onVerifyTriggerBefore;
if (verifyTriggerBeforeEvent) {
verifyTriggerBeforeEvent.call(target);
}
}
//绑定blur事件
target.onblur = function () {
//执行验证
verify(this);
};
}
}
});
};
install();
};
});
/**
*
* 表单提交模块
*
* version 1.0.2.2(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年9月22日15:17:10
*
* update log 2014年11月14日16:31:45
*
* remark 依赖于Validation模块
*
*/
Module.Create('FormSubmit', function () {
/// <summary>
/// Grid模块
/// </summary>
/** 引用需要使用的控件模块 **/
//引用Validation验证模块
var Validation = Module.Use('Validation'),
Tips = Module.Use('Tips');
var ToolTips = new Tips.RenderTips({ clickMaskHide: true });
var that = this;
that.RenderFromSubmit = function (options) {
that = this;
var FormModel = function (model) {
var that = this;
//操作表单
that.form = $(model.form || 'form').eq(0);
//依赖验证模块的自定义验证类型
that.verify = model.verify;
//提交按钮
that.submitButton = model.submitButton || 'J-form-btn-submit';
};
var FormModelInstance = new FormModel(options || {});
var install = function () {
var FormValidation = new Validation.FormValidation({
form: FormModelInstance.form,
verify: FormModelInstance.verify
});
//验证成功事件
FormValidation.onVerifySuccess(function (result) {
var target = $(this);
var message = result.message;
var customEvent = FormModelInstance.customEvent;
if (customEvent) {
var successEvent = customEvent['onVerifySuccess'];
if (successEvent) {
successEvent.call(target, result);
return false;
}
}
});
FormValidation.onAsyncVerifyBegin(function () {
var target = $(this);
});
//验证失败事件
FormValidation.onVerifyFailure(function (result) {
var target = $(this);
var message = result.message;
ToolTips.error({ message: message, timeout: 3000 });
var customEvent = FormModelInstance.customEvent;
if (customEvent) {
var failureEvent = customEvent['onVerifyFailure'];
if (failureEvent) {
failureEvent.call(target, result);
return false;
}
}
});
var formTarget = FormModelInstance.form;
that.submit = function (url) {
var customEvent = FormModelInstance.customEvent;
FormValidation.onFormTest(function (data) {
var path = url || formTarget.attr('action'),
method = (formTarget.attr('method') || 'POST').toUpperCase();
try {
var dataLoading = formTarget.attr('data-loading') || '正在提交数据,请稍等...';
RenderTip.loading(dataLoading);
} catch (e) { }
var dataAsync = formTarget.attr('data-async') || false;
if (isTrue(dataAsync)) {
$.ajax({
//请求路径
url: path,
//请求方式(POST/GET)
type: method,
//提交数据
data: data,
//返回值类型
dataType: 'text',
//请求失败
error: function (responseText, response) {
if (customEvent) {
//响应请求失败事件
var errorEvent = customEvent.onError;
if (errorEvent) {
errorEvent.call(formTarget, responseText, response);
}
}
try {
var dataError = formTarget.attr('data-error') || '操作失败!';
RenderTip.error({ message: dataError, timeout: 2000 });
} catch (e) { }
},
//请求成功
success: function (responseText, response) {
if (customEvent) {
//响应请求完成事件
var successEvent = customEvent.onSuccess;
if (successEvent) {
successEvent.call(formTarget, responseText, response);
}
}
//var dataSuccess = formTarget.attr('data-success') || '操作成功!';
//RenderTip.success({
// message: dataSuccess, timeout: 2000, callBack: function () {
// if (customEvent) {
// //响应操作完成事件
// var submitCompleteEvent = customEvent.onSubmitComplete;
// if (submitCompleteEvent) {
// var contentPanel = formTarget.parents('.J-tab-panel-content').parent();
// var tabID = contentPanel.attr('id');
// submitCompleteEvent.call(formTarget, responseText, response);
// }
// }
// }
//});
}
});
}
else {
var nodeName = formTarget[0].nodeName.toLocaleLowerCase();
var submitForm = formTarget;
if (nodeName != 'form') {
var form = target.parents('form').eq(0);
if (form.length) {
formTarget = form;
}
}
formTarget.submit();
}
});
};
formTarget.click(function (e) {
e = e || window.event;
var target = $(e.target || e.srcElement);
var customEvent = FormModelInstance.customEvent;
if (customEvent) {
var clickEvent = customEvent['onClick'];
if (clickEvent) {
clickEvent.call(target, e);
}
}
if (target.hasClass(FormModelInstance.submitButton)) {
that.submit();
}
});
that.addVerifyType = FormValidation.addVerifyType;
that.customVerify = FormValidation.customVerify;
that.asyncVerify = FormValidation.asyncVerify;
};
that.onClick = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onClick'] = fun;
}
return that;
};
that.onError = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onError'] = fun;
}
return that;
};
that.onSuccess = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onSuccess'] = fun;
}
return that;
};
that.onSubmitComplete = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onSubmitComplete'] = fun;
}
return that;
};
that.onVerifySuccess = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onVerifySuccess'] = fun;
}
return that;
};
that.onVerifyFailure = function (fun) {
if (fun) {
FormModelInstance.customEvent = FormModelInstance.customEvent || {};
FormModelInstance.customEvent['onVerifyFailure'] = fun;
}
return that;
};
install();
};
});
/**
*
* 消息提示框模块
*
* version 1.0.0.0(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年9月17日09:40:07
*
* update log 2014年9月20日17:40:54
*
*/
Module.Create('Tips', function () {
/// <summary>
/// 提示框模块
/// </summary>
var that = this;
that.RenderTips = function (options) {
/// <summary>
/// 提示框渲染类
/// </summary>
var that = this;
var TipsModel = function (model) {
var that = this;
//自定义提示框
that.tips = model.tips || null;
//自定义背景遮罩层
that.mask = model.mask || null;
//类型
that.type = model.type;
//定时器(默认为0不计时)
that.timeout = model.timeout || 0;
//消息内容
that.message = model.message || 'Tips Say...';
//回调函数(关闭时回调)
that.callBack = model.callBack || null;
//点击背景遮罩关闭弹出框
that.clickMaskHide = isTrue(model.clickMaskHide) ? true : false;
//是否自动居中定位
that.isPosition = isFalse(model.isPosition) ? false : true;
that.tips = that.tips ? $(that.tips) : null;
that.mask = that.mask ? $(that.mask) : null;
};
var TipsModelInstance = new TipsModel(options || {});
var createTips = function () {
var tips = [];
tips.push('<div class="ui-xbox-o2o">');
tips.push(' <div class="xbox-o2o-cont">');
tips.push(' <div class="ui-msg ui-msg-success-s" id="J-tips-icon">');
tips.push(' <i class="icon"></i>');
tips.push(' <div class="ui-msg-cont J-tip-cont"></div>');
tips.push(' </div>');
tips.push(' </div>');
tips.push('</div>');
tips = $(tips.join('\r\n'));
$(document.body).append(tips);
TipsModelInstance.tips = tips;
};
var createMask = function () {
//var mask = $('<div class="ui-mask" style="display:none;"><iframe class="ui-mask-iframe"></iframe></div>');
var mask = $('<div class="ui-mask"></div>');
$(document.body).append(mask);
TipsModelInstance.mask = mask;
TipsModelInstance.mask.click(function () {
if (TipsModelInstance.clickMaskHide) {
that.close();
}
});
};
var install = function () {
if (!TipsModelInstance.mask) {
createMask();
}
if (!TipsModelInstance.tips) {
createTips();
}
};
install();
//打开提示框
that.tip = function (options) {
/// <summary>
/// 打开loading提示
/// </summary>
/// <param name="options">参数对象[type, timeout, message, callBack]</param>
options = options || {};
var type = options.type || TipsModelInstance.tips,
timeout = options.timeout || TipsModelInstance.timeout,
message = options.message || TipsModelInstance.message,
callBack = options.callBack || TipsModelInstance.callBack,
isShowMask = options.isShowMask == undefined ? true : options.isShowMask,
isPosition = TipsModelInstance.isPosition;
if (TipsModelInstance.Thread) {
window.clearTimeout(TipsModelInstance.Thread);
TipsModelInstance.Thread = null;
}
var getScrollSize = scrollSize();
var width = getScrollSize.width,
height = getScrollSize.height,
bodyHeight = document.body.offsetHeight;
var mask = TipsModelInstance.mask,
tips = TipsModelInstance.tips;
if (isShowMask) {
mask.css('width', '100%').css('height', (height > bodyHeight ? height : bodyHeight) + 'px').show();
}
if (isPosition) {
tips.css('top', '50%').css('left', '50%');
}
tips.find('.J-tip-cont').html(message);
tips.find('#J-tips-icon').attr('class', 'ui-msg ui-msg-' + type + '-s');
tips.show();
var tipsWidth = tips[0].offsetWidth,
tipsHeight = tips[0].offsetHeight;
if (browser().ie == 6) {
var clientScroll = getScroll(),
getClientSize = clientSize();
var top = clientScroll.top + (getClientSize.height / 2) - (tipsHeight / 2),
left = clientScroll.left + (getClientSize.width / 2);
tips.css('position', 'absolute').css('top', top + 'px').css('left', left + 'px');
tipsWidth = tips[0].offsetWidth,
tipsHeight = tips[0].offsetHeight;
top = clientScroll.top + (getClientSize.height / 2) - (tipsHeight / 2),
left = clientScroll.left + (getClientSize.width / 2) - (tipsWidth / 2);
tips.css('top', top + 'px').css('left', left + 'px');
}
else if (isPosition) {
tips.css('margin-left', -(tipsWidth / 2) + 'px').css('margin-top', -(tipsHeight / 2) + 'px');
}
if (timeout) {
TipsModelInstance.Thread = window.setTimeout(function () {
that.close();
if (callBack) {
callBack.call(tips);
}
}, timeout);
}
return that;
};
//关闭提示框
that.close = function () {
/// <summary>
/// 关闭提示框
/// </summary>
if (TipsModelInstance.Thread) {
window.clearTimeout(TipsModelInstance.Thread);
TipsModelInstance.Thread = null;
}
if (TipsModelInstance.tips) {
TipsModelInstance.tips.hide();
}
if (TipsModelInstance.mask) {
TipsModelInstance.mask.hide();
}
return that;
};
//打开loading提示
that.loading = function (options) {
/// <summary>
/// 打开loading提示
/// </summary>
/// <param name="options">参数对象[timeout, message, callBack]</param>
options = options || {};
if (isString(options)) {
var message = options;
options = { message: message };
}
var loadingOptions = {
type: 'loading', timeout: options.timeout, message: options.message, callBack: options.callBack
};
that.tip(loadingOptions);
return that;
};
//打开error提示
that.error = function (options) {
/// <summary>
/// 打开error提示
/// </summary>
/// <param name="options">参数对象[timeout, message, callBack]</param>
options = options || {};
if (isString(options)) {
var message = options;
options = { message: message };
}
var errorOptions = {
type: 'error', timeout: options.timeout, message: options.message, callBack: options.callBack
};
that.tip(errorOptions);
return that;
};
//打开warning提示
that.warning = function (options) {
/// <summary>
/// 打开warning提示
/// </summary>
/// <param name="options">参数对象[timeout, message, callBack]</param>
options = options || {};
if (isString(options)) {
var message = options;
options = { message: message };
}
var warningOptions = {
type: 'warning', timeout: options.timeout, message: options.message, callBack: options.callBack
};
that.tip(warningOptions);
return that;
};
//打开success提示
that.success = function (options) {
/// <summary>
/// 打开success提示
/// </summary>
/// <param name="options">参数对象[timeout, message, callBack]</param>
options = options || {};
if (isString(options)) {
var message = options;
options = { message: message };
}
var successOptions = {
type: 'success', timeout: options.timeout, message: options.message, callBack: options.callBack
};
that.tip(successOptions);
return that;
};
//显示事件
that.onShow = function (fun) {
if (fun) {
TipsModelInstance.customEvent = TipsModelInstance.customEvent || {};
TipsModelInstance.customEvent['onShow'] = fun;
}
return that;
};
//关闭事件
that.onClose = function (fun) {
if (fun) {
TipsModelInstance.customEvent = TipsModelInstance.customEvent || {};
TipsModelInstance.customEvent['onClose'] = fun;
}
return that;
};
};
});
/**
*
* 弹出框模块
*
* version 1.2.2.1(主版本号.子版本号.编译版本号.修正版本号)
*
* @author pye-mail@163.com
*
* create log 2014年10月31日17:26:00
*
* update log 2014年11月11日14:55:04
*
*/
Module.Create('XBox', function () {
var that = this;
var BoxConfig = function () {
var that = this;
//是否已创建背景遮罩
that.isCreateMask = false;
//是否已显示背景遮罩
that.isShowMask = false;
//层级zIndex
that.zIndex = 1000;
//遮罩ZIndex
that.maskZIndex = that.zIndex + 1;
//弹出框个数
that.xBox = 0;
//弹出框显示个数
that.showXBox = 0;
//弹出框ZIndex
that.xBoxZIndex = that.zIndex + 2;
//当前弹出框对象
that.currentXBox = null;
//当前所有最大化状态的弹出框(用于window的resize事件问题来源当使用load加载页面嵌入iframe时给window绑定事件无效因为存在多个window[iframe中也存在不可访问(如果是跨域)的window])
that.maxXBox = {};
//所有弹出框对象
that.allXBox = {};
//背景遮罩对象
that.mask = null;
//需要特殊组合操作的键
that.handleKey = ['min', 'max', 'button'];
//ie6
that.ie6XBoxTop = null;
//提示框模板
that.template = {
//背景遮罩模板
mask: '<div class="ui-mask" style="display:none;"></div>',
//系统按钮
sysButton: '<a href="javascript:;" class="J-btn-sys ui-xbox-#KEY# #DISABLED#" data-key="#KEY#"></a>',
//自定义按钮
cusButton: '<input type="button" value="#TEXT#" class="J-btn-cus ui-btn J-btn-#KEY# #DEFAULT# #DISABLED#" data-key="#KEY#"/>',
//弹出框模板
xbox: (function () {
var html = [];
html.push('<div class="ui-xbox ui-xbox-blue" style="display:none;z-index:-1;">');
html.push('<table class="ui-xbox-w1">');
html.push(' <thead class="ui-xbox-thd">');
html.push(' <tr>');
html.push(' <td>');
html.push(' <div class="ui-xbox-hd J-xbox-drag">');
html.push(' <div class="ui-xbox-hd-w1">');
html.push(' <div class="ui-xbox-hd-w2">');
html.push(' <div class="ui-xbox-handle J-xbox-toolsBar"></div>');
html.push(' <span class="ui-xbox-title J-xbox-title">#-TITLE-#</span>');
html.push(' </div>');
html.push(' </div>');
html.push(' </div>');
html.push(' </td>');
html.push(' </tr>');
html.push(' </thead>');
html.push(' <tbody class="ui-xbox-tbd">');
html.push(' <tr><td><div class="ui-xbox-cont J-xbox-cont">#-CONTENT-#</div></td></tr>');
html.push(' </tbody>');
html.push(' <tfoot class="ui-xbox-tft">');
html.push(' <tr><td><div class="ui-xbox-ft"><div class="ui-xbox-btns J-xbox-btns"></div></div></td></tr>');
html.push(' </tfoot>');
html.push('</table>');
html.push('</div>');
return html.join('\r\n');
})(),
//消息提示模板
msgTip: (function () {
var html = [];
html.push('<div class="ui-msg ui-msg-#-TYPE-#">');
html.push(' <div class="ui-msg-cont">#-MESSAGE-#</div>');
html.push(' <div class="ui-msg-remark">#-REMARK-#</div>');
html.push('</div>');
return html.join('\r\n');
})()
};
//各种状态集合
that.status = {
//基础(未整理)
base: {},
//皮肤(未整理)
skin: {},
//默认
defaults: { min: null, max: null, close: null, yes: 'ui-btn-blue', no: 'ui-btn-gray', cancel: 'ui-btn-gray' },
//鼠标靠近
hover: { min: 'ui-xbox-min-focus', max: 'ui-xbox-max-focus', close: 'ui-xbox-close-focus', yes: 'ui-btn-blue-hover', no: 'ui-btn-gray-hover', cancel: 'ui-btn-gray-hover' },
//鼠标按下
down: { min: null, max: null, close: null, yes: null, no: null, cancel: null },
//禁用
disabled: { min: null, max: null, close: null, yes: 'ui-btn-disable', no: 'ui-btn-disable', cancel: 'ui-btn-disable' }
};
//各种自定义属性
that.dataAttr = {
//XBox唯一标识
dataIdentity: 'data-identity',
//XBox是否绑定事件
dataEventIsBind: 'data-event-isBind'
};
};
var BoxConfigInstance = new BoxConfig();
var BoxLang = function () {
var that = this;
//加载中提示语
that.loading = '正在加载,请稍后...';
that.titleLoading = '正在连接...';
//操作失败提示语
that.error = '抱歉,操作失败!';
that.titleError = '连接失败';
};
var BoxLangInstance = new BoxLang();
that.RenderBox = function (options) {
var that = this;
var BoxModel = function (model) {
var that = this;
//静态弹出框模板
that.xbox = model.xbox || null;
//静态背景遮罩
that.mask = model.mask || null;
//宽度
that.width = model.width || 200;
//高度
that.height = model.height || 50;
//初始化属性
that.initAttribute = isTrue(model.initAttribute) ? true : false;
//目标路径
that.url = model.url || null;
//加载类型(ajax|iframe)
that.loadType = model.loadType || 'ajax';
//是否加载完成
that.isCompleteLoad = false;
//加载一次
that.loadOnce = isFalse(model.loadOnce) ? false : true;
//请求附带数据集合对象
that.data = model.data || null;
//内容
that.content = model.data || '[空白面板]';
//标题
that.title = model.title || '[无标题]';
//是否可拖动
that.isDrag = isFalse(model.isDrag) ? false : true;
//每次关闭xbox时是否作为隐藏处理(true.隐藏 false.直接删除)
that.isHidden = isFalse(model.isHidden) ? false : true;
//是否为模态窗口
that.isModal = isFalse(model.isModal) ? false : true;
//是否需要背景遮罩
that.isMask = isFalse(model.isMask) ? false : true;
//是否允许改变大小
that.isResize = isTrue(model.isResize) ? true : false;
//最小宽度和高度
that.min = { width: 240, height: 60 };
//最大宽度和高度
that.max = { width: 'auto', height: 'auto' };
//将弹出框添加到
that.appendTo = model.appendTo || null;
//按钮集合
that.buttons = {
//最小化窗体
min: { type: 'system', isShow: false, isDisabled: false, text: null, callBack: null },
//最大化窗体
max: { type: 'system', isShow: false, isDisabled: false, text: null, callBack: null },
//关闭窗体
close: { type: 'system', isShow: true, isDisabled: false, text: null, callBack: null },
//肯定
yes: { type: 'custom', isShow: true, isDisabled: false, text: '确定', callBack: null },
//否定
no: { type: 'custom', isShow: true, isDisabled: false, text: '取消', callBack: null },
//还原或不改变现状
cancel: { type: 'custom', isShow: false, isDisabled: false, text: '返回', callBack: null }
};
//元素对象(表示当前实例控件的对象)
that.element = { mask: null, xbox: null, content: null, title: null, buttons: null, toolsBar: null };
//操作元素类名
that.handleClassName = { drag: 'J-xbox-drag', content: 'J-xbox-cont', title: 'J-xbox-title', buttons: 'J-xbox-btns', toolsBar: 'J-xbox-toolsBar', close: 'J-xbox-btn-close', max: 'J-xbox-btn-max', min: 'J-xbox-btn-min', restore: 'J-xbox-btn-restore', yes: 'J-xbox-btn-yes', no: 'J-xbox-btn-no', cancel: 'J-xbox-btn-cancel' };
//浏览器信息
that.browser = model.browser || browser();
//是否重写XBox中的内容(包括标题、内容和按钮,主要应用在使用静态自定义弹出框时)
that.isOverRide = isFalse(model.isOverRide) ? false : true;
//当前弹出框状态类型(默认:'default' 最小化:'min' 最大化:'max')
that.statusType = model.statusType || 'default';
//是否响应自定义事件
that.isInteraction = isFalse(model.isInteraction) ? false : true;
//弹出框显示状态
that.boxStatus = 'hide';
var buttons = model.buttons;
if (buttons) {
var buttonItem;
for (var key in buttons) {
buttonItem = buttons[key];
for (var itemKey in buttonItem) {
that.buttons[key][itemKey] = buttonItem[itemKey];
}
}
}
};
var BoxModelInstance = new BoxModel(options || {});
var createMask = function () {
if (!BoxConfigInstance.isCreateMask) {
var mask = $(BoxModelInstance.mask || BoxConfigInstance.template.mask);
$(document.body).append(mask);
//已创建背景遮罩
BoxConfigInstance.isCreateMask = true;
//未显示遮罩
BoxConfigInstance.isShowMask = false;
//保存背景遮罩对象
BoxConfigInstance.mask = mask;
BoxModelInstance.element.mask = mask;
}
else {
BoxModelInstance.element.mask = BoxConfigInstance.mask;
}
};
var createXBox = function () {
var xbox = $(BoxModelInstance.xbox || BoxConfigInstance.template.xbox),
appendTo = $(BoxModelInstance.appendTo || document.body);
var handleClassName = BoxModelInstance.handleClassName;
xbox.appendTo(appendTo);
//弹出框个数+1
BoxConfigInstance.xBox++;
//保存当前弹出框对象
BoxConfigInstance.currentXBox = xbox;
//弹出框对象
BoxModelInstance.element.xbox = xbox;
//弹出框内容区域对象
BoxModelInstance.element.content = xbox.find('.' + handleClassName.content);
//标题区域对象
BoxModelInstance.element.title = xbox.find('.' + handleClassName.title);
//按钮区域对象
BoxModelInstance.element.buttons = xbox.find('.' + handleClassName.buttons);
//工具栏区域对象
BoxModelInstance.element.toolsBar = xbox.find('.' + handleClassName.toolsBar);
var identity = Module.Guid('XBOX-IDENTITY-');
xbox.attr(BoxConfigInstance.dataAttr.dataIdentity, identity);
//保存所有弹出框
BoxConfigInstance.allXBox[identity] = xbox;
};
var bindEvent = function () {
var xbox = BoxConfigInstance.currentXBox,
dataEventIsBind = BoxConfigInstance.dataAttr.dataEventIsBind,
handleClassName = BoxModelInstance.handleClassName;
var isBind = xbox.attr(dataEventIsBind);
if (isBind != true) {
//点击事件
xbox.click(function (e) {
var target = $(eventTarget(e));
var key = target.attr('data-key');
var isDisabled = BoxConfigInstance.status.disabled[key];
var buttons = BoxModelInstance.buttons,
customEvent = BoxModelInstance.customEvent;
if (!target.hasClass(isDisabled)) {
if (target.hasClass(handleClassName.close)) {
//关闭
var closeButton = buttons[key];
if (!closeButton.isDisabled) {
close(closeButton.callBack);
}
}
else if (target.hasClass(handleClassName.yes)) {
//确定按钮
var yesButton = buttons[key];
if (!yesButton.isDisabled) {
var yesEvent = null;
if (customEvent) {
yesEvent = customEvent['onYes'];
}
var yesCallBack = function () {
var callBackResult = true, eventResult = true, result = true;
if (yesButton.callBack) {
callBackResult = yesButton.callBack.call(BoxModelInstance.element.xbox);
if (isFalse(callBackResult)) {
result = false;
}
}
if (yesEvent) {
eventResult = yesEvent.call(BoxModelInstance.element.xbox);
if (isFalse(eventResult)) {
result = false;
}
}
return result;
};
close(yesCallBack);
}
}
else if (target.hasClass(handleClassName.no)) {
//否定按钮
var noButton = buttons[key];
if (!noButton.isDisabled) {
var noEvent = null;
if (customEvent) {
noEvent = customEvent['onNo'];
}
var noCallBack = function () {
var callBackResult = true, eventResult = true, result = true;
if (noButton.callBack) {
callBackResult = noButton.callBack.call(BoxModelInstance.element.xbox);
if (isFalse(callBackResult)) {
result = false;
}
}
if (noEvent) {
eventResult = noEvent.call(BoxModelInstance.element.xbox);
if (isFalse(eventResult)) {
result = false;
}
}
return result;
};
close(noCallBack);
}
}
else if (target.hasClass(handleClassName.cancel)) {
//取消按钮
var cancelButton = buttons[key];
if (!cancelButton.isDisabled) {
var cancelEvent = null;
if (customEvent) {
cancelEvent = customEvent['onCancel'];
}
var cancelCallBack = function () {
var callBackResult = true, eventResult = true, result = true;
if (cancelButton.callBack) {
callBackResult = cancelButton.callBack.call(BoxModelInstance.element.xbox);
if (isFalse(callBackResult)) {
result = false;
}
}
if (cancelEvent) {
eventResult = cancelEvent.call(BoxModelInstance.element.xbox);
if (isFalse(eventResult)) {
result = false;
}
}
return result;
};
close(cancelCallBack);
}
}
}
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var clickEvent = customEvent.onClick;
if (clickEvent) {
clickEvent.call(target, e);
}
}
});
//mouseover事件
xbox.mouseover(function (e) {
var target = $(eventTarget(e));
});
//mousedown事件
xbox.mousedown(function (e) {
var target = $(eventTarget(e));
});
xbox.attr(dataEventIsBind, true);
}
};
var drag = function (opts) {
var dragOptions = {
//拖动触发元素
drag: null,
//拖动移动元素如果为null默认为drag对象
move: null,
//拖动范围限制区域
region: document.body
}, browserInfo = BoxModelInstance.browser;
//遍历自定义参数
if (opts) {
for (var key in opts) { dragOptions[key.toLocaleLowerCase()] = opts[key]; }
//如果移动对象为空
if (!dragOptions.move) { dragOptions.move = dragOptions.drag; }
}
var dragEvent = function (event) {
event = event || window.event;
//获取移动元素的相对坐标
var movePosition = getPosition(dragOptions.move);
//响应拖动事件
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var dragEvent = customEvent.onDrag;
if (dragEvent && BoxModelInstance.isInteraction) {
var eventResult = dragEvent.call(BoxModelInstance.element.xbox, event, movePosition.top, movePosition.left);
if (eventResult == false || eventResult == 'false' || eventResult == 'False') {
return false;
}
}
}
//判断移动元素是否为浮动元素
dragOptions.drag.style.cursor = 'move';
//获取拖动限制区域相对坐标
var regionPosition = getPosition(dragOptions.region);
var regionTop = regionPosition.top, regionLeft = regionPosition.left;
var moveStyle = dragOptions.move.style;
if (browserInfo.ie !== '6.0') {
moveStyle.position = 'absolute';
moveStyle.top = movePosition.top + 'px';
moveStyle.left = movePosition.left + 'px';
moveStyle.margin = '0px';
}
//获取移动元素的宽和高
var moveWidth = dragOptions.move.offsetWidth, moveHeight = dragOptions.move.offsetHeight;
//移动元素在限制区域的最小坐标
var minTop = 0, minLeft = 0;
//移动元素在限制区域的最大坐标
var scrolls = getScroll();
var clients = clientSize();
var maxTop = clients.height + scrolls.top - moveHeight,
maxLeft = clients.width + scrolls.left - moveWidth;
//初始化鼠标坐标
var dragClientX = event.clientX, dragClientY = event.clientY;
//定义元素移动距离
var top, left;
//鼠标移动事件
document.onmousemove = function (e) {
e = e || window.event;
//获取鼠标当前坐标位置
var moveClientX = e.clientX, moveClientY = e.clientY;
top = movePosition.top + moveClientY - dragClientY, left = movePosition.left + moveClientX - dragClientX;
if (top <= minTop) { top = minTop; }
if (top >= maxTop) { top = maxTop; }
if (left <= minLeft) { left = minLeft; }
if (left >= maxLeft) { left = maxLeft; }
moveStyle.top = top + 'px';
moveStyle.left = left + 'px';
//响应控件移动事件
if (customEvent) {
var moveEvent = customEvent.onDragMove;
if (moveEvent) {
moveEvent.call(BoxModelInstance.element.xbox, e, top, left);
}
}
};
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
dragOptions.drag.style.cursor = 'default';
BoxModelInstance.ie6XBoxTop = parseInt(moveStyle.top) - getScroll().top;
if (browserInfo.ie !== '6.0') {
moveStyle.top = BoxModelInstance.ie6XBoxTop + 'px';
moveStyle.position = 'fixed';
}
movePosition = getPosition(dragOptions.move);
if (customEvent) {
var dragEndEvent = customEvent.onDragEnd;
//响应控件拖拽结束事件
if (dragEndEvent) {
dragEndEvent.call(BoxModelInstance.element.xbox, e, movePosition.top, movePosition.left);
}
}
};
};
//绑定事件
if (dragOptions.drag) { dragOptions.drag.onmousedown = dragEvent; }
};
var show = function (callBack) {
var xbox = BoxModelInstance.element.xbox,
mask = BoxModelInstance.element.mask;
if (!xbox) {
var buttons = options.buttons;
if (buttons) {
var buttonItem;
for (var key in buttons) {
buttonItem = buttons[key];
for (var itemKey in buttonItem) {
BoxModelInstance.buttons[key][itemKey] = buttonItem[itemKey];
}
}
}
install();
xbox = BoxModelInstance.element.xbox;
}
//弹出框zindex+2
BoxConfigInstance.xBoxZIndex += 2;
xbox.css('z-index', BoxConfigInstance.xBoxZIndex).show();
//弹出框显示个数+1
BoxConfigInstance.showXBox++;
if (BoxModelInstance.isMask) {
BoxConfigInstance.maskZIndex += 2;
mask.css('z-index', BoxConfigInstance.maskZIndex).show();
BoxConfigInstance.isShowMask = true;
}
BoxModelInstance.boxStatus = 'show';
renderBoxPosition();
if (callBack && isFunction(callBack)) {
callBack();
}
//响应显示事件
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var showEvent = customEvent.onShow;
if (showEvent && BoxModelInstance.isInteraction) {
var eventResult = showEvent.call(BoxModelInstance.element.xbox);
if (eventResult == false || eventResult == 'false' || eventResult == 'False') {
return that;
}
}
}
return that;
};
var close = function (callBack) {
if (BoxModelInstance.boxStatus === 'show') {
if (callBack && isFunction(callBack)) {
//执行自定义操作
var eventResult = callBack.call(BoxModelInstance.element.xbox);
if (eventResult == false || eventResult == 'false' || eventResult == 'False') {
return that;
}
}
//响应关闭事件
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var closeEvent = customEvent.onClose;
if (closeEvent && BoxModelInstance.isInteraction) {
var eventResult = closeEvent.call(BoxModelInstance.element.xbox);
if (eventResult == false || eventResult == 'false' || eventResult == 'False') {
return that;
}
}
}
//ZIndex递减
BoxConfigInstance.xBoxZIndex -= 2, BoxConfigInstance.maskZIndex -= 2;
if (BoxModelInstance.isHidden) {
//隐藏弹出框
BoxModelInstance.element.xbox.hide();
//设置xbox状态
BoxModelInstance.boxStatus = 'hide';
//弹出框显示个数减一
BoxConfigInstance.showXBox--;
//如果是链接加载页面,关闭时终止页面的加载
if (BoxModelInstance.url && !BoxModelInstance.isCompleteLoad) {
that.stopLoad();
}
}
else {
//删除弹出框,并设置状态
BoxModelInstance.element.xbox.remove();
BoxModelInstance.element.xbox = null;
BoxModelInstance.boxStatus = 'remove';
//弹出框个数减一、显示个数减一
BoxConfigInstance.showXBox--;
BoxConfigInstance.xBox--;
//
if (BoxModelInstance.next) {
BoxModelInstance.next.idx = 0;
}
}
if (BoxConfigInstance.showXBox > 0) {
BoxModelInstance.element.mask.css('z-index', BoxConfigInstance.maskZIndex);
//如果存在非模态窗口
}
else {
//隐藏背景遮罩
BoxModelInstance.element.mask.hide();
BoxConfigInstance.isShowMask = false;
}
}
return that;
};
var renderButton = function (buttons, overRide) {
if (isBoolean(buttons)) {
overRide = buttons;
buttons = null;
}
if (overRide || overRide == undefined || overRide == null) {
if (buttons) {
var boxButtons = null, btns = null;
for (var key in buttons) {
boxButtons = BoxModelInstance.buttons[key];
btns = buttons[key];
for (var btnKey in btns) {
boxButtons[btnKey] = btns[btnKey];
}
}
}
buttons = BoxModelInstance.buttons;
var sysButton = BoxConfigInstance.template.sysButton,
cusButton = BoxConfigInstance.template.cusButton,
disabled = BoxConfigInstance.status.disabled,
defaults = BoxConfigInstance.status.defaults,
handleClassName = BoxModelInstance.handleClassName,
item, handleLink, btnButton;
var toolsBar = BoxModelInstance.element.toolsBar.html(''),
xboxButton = BoxModelInstance.element.buttons.html('');
var showCount = 0;
for (var key in buttons) {
item = buttons[key];
if (item.isShow) {
if (item.type == 'system') {
handleLink = $(sysButton.replaceAll('#KEY#', key)
.replace('#DISABLED#', (item.isDisabled ? (disabled[key] ? disabled[key] : '') : '')));
handleLink.addClass(handleClassName[key]);
toolsBar.append(handleLink);
}
else if (item.type == 'custom') {
btnButton = $(cusButton.replaceAll('#KEY#', key)
.replace('#TEXT#', item.text || '')
.replace('#DEFAULT#', defaults[key] || '')
.replace('#DISABLED#', (item.isDisabled ? (disabled[key] || '') : '')));
btnButton.addClass(handleClassName[key]);
xboxButton.append(btnButton);
}
showCount++;
}
}
if (!showCount) {
xboxButton.parents('tfoot').hide();
}
}
};
var renderButtonKey = function () {
var toolsBar = BoxModelInstance.element.toolsBar,
xboxButton = BoxModelInstance.element.buttons,
handleClassName = BoxModelInstance.handleClassName;
toolsBar.find('.' + handleClassName.close).addClass('J-btn-sys').attr('data-key', 'close');
toolsBar.find('.' + handleClassName.min).addClass('J-btn-sys').attr('data-key', 'min');
toolsBar.find('.' + handleClassName.max).addClass('J-btn-sys').attr('data-key', 'max');
toolsBar.find('.' + handleClassName.restore).addClass('J-btn-sys').attr('data-key', 'restore');
xboxButton.find('.' + handleClassName.yes).addClass('J-btn-cus').attr('data-key', 'yes');
xboxButton.find('.' + handleClassName.no).addClass('J-btn-cus').attr('data-key', 'no');
xboxButton.find('.' + handleClassName.cancel).addClass('J-btn-cus').attr('data-key', 'cancel');
};
var renderBoxPosition = function () {
var mask = BoxModelInstance.element.mask,
xbox = BoxModelInstance.element.xbox;
//获取浏览器内容区域的宽和高
var scroller = scrollSize();
mask.css('width', (scroller.width) + 'px').css('height', (scroller.height) + 'px');
var contentTarget = BoxModelInstance.element.content;
contentTarget.css('width', 'auto').css('height', 'auto');
if (BoxModelInstance.url === null || BoxModelInstance.isCompleteLoad || BoxModelInstance.initAttribute) {
//设置最小宽度和高度
var contentWidth = contentTarget[0].offsetWidth, contentHeight = contentTarget[0].offsetHeight;
var min = BoxModelInstance.min, max = BoxModelInstance.max;
var minWidth = min.width, minHeight = min.height,
maxWidth = max.width, maxHeight = max.height;
var width = BoxModelInstance.width,
height = BoxModelInstance.height;
if (minWidth != 'auto') {
if (contentWidth <= minWidth) {
if (minWidth < width) {
contentTarget.css('width', width + 'px').css('overflow', 'auto');
}
else {
contentTarget.css('width', minWidth + 'px').css('overflow', 'auto');
}
}
else if (width > contentWidth) {
contentTarget.css('width', width + 'px').css('overflow', 'auto');
}
}
if (minHeight != 'auto') {
if (contentHeight <= minHeight) {
if (minHeight < height) {
contentTarget.css('height', height + 'px').css('overflow', 'auto');
}
else {
contentTarget.css('height', minHeight + 'px').css('overflow', 'auto');
}
}
else if (height > contentHeight) {
contentTarget.css('height', height + 'px').css('overflow', 'auto');
}
}
if (maxWidth != 'auto') {
if (contentWidth >= maxWidth) {
contentTarget.css('width', maxWidth + 'px').css('overflow', 'auto');
}
else if (width > maxWidth) {
contentTarget.css('width', maxWidth + 'px').css('overflow', 'auto');
}
}
if (maxHeight != 'auto') {
if (contentHeight <= maxHeight) { contentTarget.css('height', maxHeight + 'px').css('overflow', 'auto'); }
}
}
var width = xbox[0].offsetWidth, height = xbox[0].offsetHeight;
if (BoxModelInstance.browser.ie !== '6.0') {
xbox.css('left', '50%');
xbox.css('top', '50%');
xbox.css('margin', '-' + (height / 2) + 'px ' + '-' + (width / 2) + 'px');
}
else {
//获取浏览器可见区域的宽和高
var clients = clientSize();
//获取滚动条距离
var scrollBar = getScroll();
xbox.css('left', ((clients.width / 2) - (width / 2) + scrollBar.left) + 'px');
xbox.css('top', ((clients.height / 2) - (height / 2) + scrollBar.top) + 'px');
}
};
var renderTitle = function (title, overRide) {
if (isBoolean(title)) {
overRide = title;
title = null;
}
if (overRide || overRide == undefined || overRide == null) {
title = title || BoxModelInstance.title;
var xbox = BoxModelInstance.element.xbox;
if (xbox) {
if (title) {
BoxModelInstance.element.title.html(title);
}
else {
BoxModelInstance.element.title.parents('thead').hide();
}
}
}
else {
BoxModelInstance.title = BoxModelInstance.element.title.html();
}
};
var renderContent = function (content, overRide) {
if (isBoolean(content)) {
overRide = content;
content = BoxModelInstance.content;
}
if (overRide || overRide == undefined || overRide == null) {
content = content || BoxModelInstance.content;
var xbox = BoxModelInstance.element.xbox;
if (xbox) {
if (isString(content)) {
BoxModelInstance.element.content.html(content);
}
else {
BoxModelInstance.element.content.append(content);
}
renderBoxPosition();
}
}
else {
BoxModelInstance.content = BoxModelInstance.element.content.html();
}
};
var saveHistory = function (options) {
var boxLoadHistory = {
//URL
url: options.url,
//标题
title: options.title,
//数据
data: options.data,
//请求方式
loadType: options.loadType,
//宽
width: options.width,
//高
height: options.height,
//按钮
buttons: options.buttons,
//其他属性(非BoxModelInstance中的属性)
other: options.other
};
if (!BoxModelInstance.loadHistory) {
BoxModelInstance.loadHistory = {
//历史记录信息集合
history: [boxLoadHistory],
//当前记录位置下标从0开始
index: 0
};
}
else {
//判断是否已经存在
var history = BoxModelInstance.loadHistory.history;
var i = 0, length = history.length, historyItem, status = true;
for (; i < length; i++) {
historyItem = history[i];
if (historyItem['url'] == boxLoadHistory['url']) {
status = false;
break;
}
}
if (status) {
BoxModelInstance.loadHistory.history.push(boxLoadHistory);
}
}
};
var clearHistory = function (url) {
if (url) {
var history = BoxModelInstance.loadHistory.history,
index = BoxModelInstance.loadHistory.index;
var i = 0, length = history.length, historyItem, tempHistory = [];
for (; i < length; i++) {
historyItem = history[i];
if (historyItem['url'] != url) {
//重新组合记录
tempHistory.push(historyItem);
}
else {
//重新设置记录当前位置下标
if (index > i) {
BoxModelInstance.loadHistory.index -= 1;
}
}
}
//重新设置历史记录
BoxModelInstance.loadHistory.history = tempHistory;
}
else {
BoxModelInstance.loadHistory = {
//历史记录信息集合
history: [],
//当前记录位置下标从0开始
index: 0
};
}
};
var loadPage = function (options) {
options = options || {};
if (options.data) {
//重置请求提交数据
BoxModelInstance.data = options.data;
}
if (options.url) {
//重置请求路径
BoxModelInstance.url = options.url;
}
if (options.loadType) {
//重置加载类型
BoxModelInstance.loadType = options.loadType;
}
if (options.title) {
//重置标题
BoxModelInstance.title = options.title;
}
BoxModelInstance.next = null;
//失败
var error = options.error,
//完成
complete = options.complete,
//成功
success = options.success,
//是否缓存数据
isCache = options.isCache;
if (isCache != false) {
//保存历史记录
saveHistory({
url: BoxModelInstance.url,
data: BoxModelInstance.data,
title: BoxModelInstance.title,
loadType: BoxModelInstance.loadType,
width: BoxModelInstance.width,
height: BoxModelInstance.height,
buttons: BoxModelInstance.buttons,
other: {
error: error,
complete: complete,
success: success
}
});
}
//自定义事件
var customEvent = BoxModelInstance.customEvent;
if (BoxModelInstance.boxStatus == 'hide') {
show();
}
if (BoxModelInstance.loadOnce) {
if (BoxModelInstance.isCompleteLoad) {
return that;
}
}
//设置加载状态
BoxModelInstance.isCompleteLoad = false;
//设置加载模板
var loading = BoxConfigInstance.template.msgTip.replace('#-TYPE-#', 'loading').replace('#-MESSAGE-#', BoxLangInstance.loading).replace('#-REMARK-#', '');
renderContent(loading, true);
renderTitle(BoxLangInstance.titleLoading);
//保持最大化
if (BoxModelInstance.statusType === 'max') {
var thisInteraction = BoxModelInstance.isInteraction;
BoxModelInstance.isInteraction = false;
that.reMax();
BoxModelInstance.isInteraction = thisInteraction;
}
var loadType = BoxModelInstance.loadType.toLocaleLowerCase();
if (loadType == 'iframe') {
//嵌入iframe方式
var iframes = document.createElement('iframe');
$(iframes).attr('frameBorder', 'none')
.css('display', 'none')
.css('border', 'none')
.css('width', '100%')
.css('height', '98%');
BoxModelInstance.content = $(iframes);
BoxModelInstance.element.content.append($(iframes));
iframes.onload = function () {
renderTitle(BoxModelInstance.title);
$(iframes).show();
BoxModelInstance.element.content.find('.ui-msg').remove();
//设置加载完成
BoxModelInstance.isCompleteLoad = true;
renderBoxPosition();
//保持最大化
if (BoxModelInstance.statusType === 'max') {
var thisInteraction = BoxModelInstance.isInteraction;
BoxModelInstance.isInteraction = false;
that.reMax();
BoxModelInstance.isInteraction = thisInteraction;
}
if (success) {
success.call(that);
}
if (customEvent) {
var loadEvent = customEvent.onLoad;
//响应加载完成事件
if (loadEvent && BoxModelInstance.isInteraction) {
loadEvent.call(BoxModelInstance.element.xbox);
}
}
};
var data = BoxModelInstance.data,
url = BoxModelInstance.url;
if (data) {
var dataString = '';
for (var key in data) {
if (dataString == '') {
dataString = '?' + key + '=' + data[key];
}
else {
dataString += '&' + key + '=' + data[key];
}
}
url = url + dataString;
}
iframes.src = url;
}
else if (loadType == 'ajax') {
var method = BoxModelInstance.url.substring(BoxModelInstance.url.length - 5, BoxModelInstance.url.length) == '.html' ? 'GET' : 'POST';
//加载内容
BoxModelInstance.ajaxRequired = $.ajax({
//请求路径
url: BoxModelInstance.url,
//请求方式(POST/GET)
method: method,
//同步(false)/异步(true)
async: true,
//提交数据
data: BoxModelInstance.data,
//请求出错
error: function (responseText, response) {
renderTitle(BoxLangInstance.titleError);
var errors = BoxConfigInstance.template.msgTip.replace('#-TYPE-#', 'error').replace('#-MESSAGE-#', BoxLangInstance.error).replace('#-REMARK-#', '');
BoxModelInstance.element.content.html(error);
renderBoxPosition();
//保持最大化
if (BoxModelInstance.statusType == 'max') {
var thisInteraction = BoxModelInstance.isInteraction;
BoxModelInstance.isInteraction = false;
that.reMax();
BoxModelInstance.isInteraction = thisInteraction;
}
if (error) {
error.call(BoxModelInstance.element.xbox, responseText, response);
}
},
//请求完成
complete: function (responseText, response) {
if (complete) {
complete.call(BoxModelInstance.element.xbox);
}
},
//请求成功
success: function (responseText, response) {
renderTitle(BoxModelInstance.title);
BoxModelInstance.content = responseText
BoxModelInstance.element.content.html(responseText);
//保持最大化
if (BoxModelInstance.statusType === 'max') {
var thisInteraction = BoxModelInstance.isInteraction;
BoxModelInstance.isInteraction = false;
that.reMax();
BoxModelInstance.isInteraction = thisInteraction;
}
//设置加载完成
BoxModelInstance.loadComplete = true;
renderBoxPosition();
if (Module.asyncRunHandle) {
Module.asyncRunHandle();
}
if (success) {
success.call(BoxModelInstance.element.xbox, responseText, response);
}
if (customEvent) {
var loadEvent = customEvent.onLoad;
//响应加载完成事件
if (loadEvent && BoxModelInstance.isInteraction) {
loadEvent.call(BoxModelInstance.element.xbox, responseText, response);
}
}
}
});
}
return that;
};
var renderLoad = function (options) {
var loadType = options.loadType,
url = options.url,
data = options.data,
callBack = options.callBack;
};
var createNextPanel = function (option, callBack) {
var optionID = option.id;
BoxModelInstance.next = BoxModelInstance.next || {
list: {},
keys: [],
idx: 0
};
var tempPanel = '<div class="J-xbox-next-panel J-xbox-next-panel-#OPTIONID#" style="width:100%;height:97%;"></div>';
var xboxContent = BoxModelInstance.element.content;
if (BoxModelInstance.next.keys.length == 0) {
//var defaultContent = BoxModelInstance.content;
var tempContent = $(tempPanel.replace('#OPTIONID#', 'default')).append(xboxContent.children()).hide();
xboxContent.html('').append(tempContent);
var defaultOptions = {
id: 'default',
title: BoxModelInstance.title,
content: BoxModelInstance.content,
buttons: {}
};
var defaultButtons = BoxModelInstance.buttons, defaultItem;
for (var key in defaultButtons) {
defaultItem = defaultButtons[key];
defaultOptions.buttons[key] = {};
for (var defaultKey in defaultItem) {
defaultOptions.buttons[key][defaultKey] = defaultItem[defaultKey];
}
}
BoxModelInstance.next.list['default'] = defaultOptions;
BoxModelInstance.next.keys.push('default');
//BoxModelInstance.next.idx++;
}
if (!BoxModelInstance.next.list[optionID]) {
BoxModelInstance.next.list[optionID] = option;
BoxModelInstance.next.keys.push(optionID);
BoxModelInstance.next.idx++;
}
var nextPanel = xboxContent.find('.J-xbox-next-panel-' + optionID);
if (!nextPanel.length) {
nextPanel = $(tempPanel.replace('#OPTIONID#', optionID));
nextPanel.html('');
}
xboxContent.find('.J-xbox-next-panel').hide();
xboxContent.append(nextPanel);
var content = option.content,
target = option.target,
url = option.url;
if (content) {
//静态内容
nextPanel.html(content);
if (callBack && isFunction(callBack)) {
callBack.call(that);
}
if (option.callBack && isFunction(option.callBack)) {
option.callBack.call(that);
}
}
else if (target && target.length) {
//目标元素
nextPanel.append(target);
if (callBack && isFunction(callBack)) {
callBack.call(that);
}
if (option.callBack && isFunction(option.callBack)) {
option.callBack.call(that);
}
}
else if (url) {
//地址请求
var data = option.data,
loadType = option.loadType;
//设置加载模板
var loading = BoxConfigInstance.template.msgTip.replace('#-TYPE-#', 'loading').replace('#-MESSAGE-#', BoxLangInstance.loading).replace('#-REMARK-#', '');
nextPanel.append(loading);
if (loadType == 'iframe') {
//嵌入iframe方式
var iframes = document.createElement('iframe');
$(iframes).attr('frameBorder', 'none')
.css('display', 'none')
.css('border', 'none')
.css('width', '100%')
.css('height', '100%');
if (data) {
var dataString = '';
for (var key in data) {
if (dataString == '') {
dataString = '?' + key + '=' + data[key];
}
else {
dataString += '&' + key + '=' + data[key];
}
}
url = url + dataString;
}
iframes.onload = function () {
nextPanel.find('.ui-msg').remove();
$(iframes).show();
if (callBack && isFunction(callBack)) {
callBack.call(that);
}
if (option.callBack && isFunction(option.callBack)) {
option.callBack.call(that);
}
};
iframes.src = url;
nextPanel.append(iframes);
}
else if (loadType == 'ajax') {
var method = url.substring(url.length - 5, url.length) == '.html' ? 'GET' : 'POST';
//加载内容
BoxModelInstance.ajaxRequired = $.ajax({
//请求路径
url: url,
//请求方式(POST/GET)
method: method,
//同步(false)/异步(true)
async: true,
//提交数据
data: data,
//请求出错
error: function (responseText, response) {
var errors = BoxConfigInstance.template.msgTip.replace('#-TYPE-#', 'error').replace('#-MESSAGE-#', BoxLangInstance.error).replace('#-REMARK-#', '');
nextPanel.html(errors);
},
//请求完成
complete: function (responseText, response) { },
//请求成功
success: function (responseText, response) {
nextPanel.html(responseText);
if (Module.asyncRunHandle) {
Module.asyncRunHandle();
}
if (callBack && isFunction(callBack)) {
callBack.call(that);
}
if (option.callBack && isFunction(option.callBack)) {
option.callBack.call(that);
}
}
});
}
}
};
var install = function () {
//创建背景遮罩
createMask();
//创建XBox
createXBox();
//创建按钮
renderButton(BoxModelInstance.isOverRide);
//设置标题
renderTitle(BoxModelInstance.isOverRide);
//设置内容
renderContent(BoxModelInstance.isOverRide);
renderButtonKey();
//绑定事件
bindEvent();
var xbox = BoxModelInstance.element.xbox;
//拖动事件
if (BoxModelInstance.isDrag) {
var dragTarget = xbox.find('.J-xbox-drag');
drag({ drag: dragTarget[0], move: xbox[0] });
}
//IE6滚动
if (BoxModelInstance.browser.ie === '6.0') {
var clientHeight = clientSize().height;
var xBoxTop = (clientHeight - xbox.offsetHeight) / 2;
var scrollTop;
xbox.css('position', 'absolute').css('margin', '0px').css('top', xBoxTop + 'px');
var scroll = function () {
var osHeight = xbox.offsetHeight;
xBoxTop = BoxModelInstance.ie6XBoxTop || (clientSize().height - osHeight) / 2;
scrollTop = getScroll().top;
xbox.css('top', (scrollTop + xBoxTop) + 'px');
};
window.onscroll = scroll;
scroll();
}
};
that.open = show;
that.close = close;
that.load = loadPage;
that.reLoad = function () {
if (BoxModelInstance.url) {
//动态加载
var loadHistory = BoxModelInstance.loadHistory;
var history = loadHistory.history;
var historyData = history[loadHistory.index];
//重新加载历史记录
loadPage({ other: historyData['other'], isCache: false });
}
else {
//静态内容
renderContent();
show();
}
return that;
};
that.stopLoad = function (callBack) {
var ajaxRequired = BoxModelInstance.ajaxRequired,
loadType = BoxModelInstance.loadType.toLocaleLowerCase();
if (loadType == 'iframe') {
//终止iframe嵌入(移除元素)
BoxModelInstance.element.content.html('');
}
else if (loadType == 'ajax') {
if (ajaxRequired) {
ajaxRequired.abort();
}
}
if (callBack) {
callBack();
}
return that;
};
that.history = function (back) {
if (back == undefined || back == null || back == 'null' || back == 'undefined') {
back = -1;
}
var loadHistory = BoxModelInstance.loadHistory;
if (loadHistory) {
var history = loadHistory.history;
var historyLength = history.length;
loadHistory.index += back;
if (loadHistory.index < 0) {
loadHistory.index = 0;
}
else if (loadHistory.index > historyLength) {
loadHistory.index = historyLength;
}
//获取历史记录数据
var historyData = history[loadHistory.index];
//重置Box相关属性
for (var key in historyData) {
if (key != 'other') {
BoxModelInstance[key] = historyData[key];
}
}
//重新加载历史记录
loadPage({ other: historyData['other'], isCache: false });
}
return that;
};
that.title = function (title, callBack) {
renderTitle(title);
if (callBack && isFunction(callBack)) {
callBack();
}
return that;
};
that.button = function (buttons, callBack) {
renderButton(buttons);
if (callBack && isFunction(callBack)) {
callBack();
}
return that;
};
that.content = function (content, callBack) {
renderContent(content);
if (callBack && isFunction(callBack)) {
callBack();
}
return that;
};
that.contentGroup = function (options) {
BoxModelInstance.next = BoxModelInstance.next || {
list: {},
keys: [],
idx: -1
};
if (options) {
var i = 0, length = options.length, item, id;
for (; i < length; i++) {
item = options[i];
id = item.id;
if (!BoxModelInstance.next[id]) {
BoxModelInstance.next[id] = item;
BoxModelInstance.next.keys.push(id);
}
}
}
return that;
};
that.goToNext = function (flag) {
flag = flag == undefined || flag == null ? 1 : flag;
var toNext = BoxModelInstance.next;
if (toNext) {
var keys = toNext.keys,
list = toNext.list,
idx = toNext.idx;
var keyIdx = idx + flag;
var renderNextBox = function () {
renderTitle(nextkey.title);
var buttons = nextItem.buttons, btnItem;
if (buttons) {
for (var key in buttons) {
btnItem = buttons[key];
for (var btnKey in btnItem) {
BoxModelInstance.buttons[key][btnKey] = btnItem[btnKey];
}
}
renderButton();
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var prevEvent = customEvent.onPrev;
if (prevEvent) {
prevEvent.call(that);
}
}
}
};
var xboxContent = BoxModelInstance.element.content;
if (keyIdx >= 0) {
var nextkey = keys[keyIdx];
if (nextkey) {
var nextItem = list[nextkey];
if (nextItem) {
var optionID = nextItem.id;
xboxContent.find('.J-xbox-next-panel').hide();
//当前项的元素(数据来源有可能来自contentGroup中添加的可能所有数据并没有创建元素)
var nextPanel = xboxContent.find('.J-xbox-next-panel-' + optionID);
if (nextPanel.length) {
xboxContent.find('.J-xbox-next-panel-' + optionID).show();
toNext.idx = keyIdx;
renderNextBox();
}
else {
createNextPanel(nextItem, renderNextBox);
}
}
}
}
}
return that;
};
that.next = function (options) {
if (options) {
var optionID = options.id;
if (!optionID) {
//ID为必填
Module.Error('未指定ID[弹出框内容切换]');
return that;
}
var baseOptions = {};
//唯一ID
baseOptions.id = optionID;
//静态内容(显示级别1)
baseOptions.content = options.content;
//目标元素(显示级别2)
baseOptions.target = $(options.target);
//请求地址(显示级别3)
baseOptions.url = options.url;
//提交数据
baseOptions.data = options.data;
//如果是url加载类型(ajax||iframe)
baseOptions.loadType = options.loadType || 'ajax';
//请求一次,下次再打开这个地址时,则不再请求
baseOptions.isLoadOnce = isFalse(options.isLoadOnce) ? false : true;
//回调函数
baseOptions.callBack = options.callBack;
//ajax加载状态(0.初始||1.加载中||2.加载完成)
//baseOptions.loadStatus = 0;
//标题
baseOptions.title = options.title;
//按钮
baseOptions.buttons = options.buttons;
//form表单
baseOptions.form = null;
if (options.form) {
baseOptions.form = {
//提交地址
path: options.form.path,
//提交方式(POST||GET)
method: options.form.method || 'POST',
//提交类型(submit||ajax)
submitType: options.form.submitType || 'submit',
//提交前事件
submitBefore: options.form.submitBefore,
//提交失败(只针对ajax提交)
submitError: options.form.submitError,
//提交成功(只针对ajax提交)
submitSuccess: options.form.submitSuccess
};
}
var xboxContent = BoxModelInstance.element.content;
var boxNext = BoxModelInstance.next;
var renderCallBack = function () {
renderTitle(baseOptions.title);
var buttons = baseOptions.buttons, btnItem;
if (buttons) {
for (var key in buttons) {
btnItem = buttons[key];
for (var btnKey in btnItem) {
BoxModelInstance.buttons[key][btnKey] = btnItem[btnKey];
}
}
renderButton();
var customEvent = BoxModelInstance.customEvent;
if (customEvent) {
var nextEvent = customEvent.onNext;
if (nextEvent) {
nextEvent.call(that);
}
}
}
};
if (boxNext) {
var historyBoxNext = boxNext.list[optionID];
if (historyBoxNext) {
renderCallBack();
//如果已创建内容,直接显示
xboxContent.find('.J-xbox-next-panel').hide();
xboxContent.find('.J-xbox-next-panel-' + optionID).show();
BoxModelInstance.next.idx++;
if (options.callBack && isFunction(options.callBack)) {
options.callBack.call(that);
}
return that;
}
}
createNextPanel(baseOptions, renderCallBack);
}
else {
goToNext();
}
return that;
};
that.prev = function () {
that.goToNext(-1);
return that;
};
that.max = function () { };
that.reMax = function () { };
that.moveTo = function () { };
that.resizeBy = function () { };
that.alert = function (options, sure) {
var thisOptions = { message: '[空]', type: 'default', title: '提示消息', remark: '', sure: null };
if (isString(options)) {
thisOptions.message = options;
if (sure && isFunction(sure)) {
thisOptions.sure = sure;
}
}
else if (isJSON(options)) {
for (var key in options) {
thisOptions[key] = options[key];
}
}
var message = BoxConfigInstance.template.msgTip;
if (thisOptions.type == 'warn') {
thisOptions.type = 'warning';
}
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 360;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.yes.callBack = thisOptions.sure;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
};
that.success = function (options, sure) {
var thisOptions = { message: '[空]', type: 'success', title: '提示消息', remark: '', sure: null };
if (isString(options)) {
thisOptions.message = options;
if (sure && isFunction(sure)) {
thisOptions.sure = sure;
}
}
else if (isJSON(options)) {
for (var key in options) {
if (key != 'type') {
thisOptions[key] = options[key];
}
}
}
var message = BoxConfigInstance.template.msgTip;
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 360;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.yes.callBack = thisOptions.sure;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
};
that.warn = function (options, sure) {
var thisOptions = { message: '[空]', type: 'warning', title: '提示消息', remark: '', sure: null };
if (isString(options)) {
thisOptions.message = options;
if (sure && isFunction(sure)) {
thisOptions.sure = sure;
}
}
else if (isJSON(options)) {
for (var key in options) {
if (key != 'type') {
thisOptions[key] = options[key];
}
}
}
var message = BoxConfigInstance.template.msgTip;
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 360;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.yes.callBack = thisOptions.sure;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
};
that.help = function (options, sure) {
var thisOptions = { message: '[空]', type: 'help', title: '提示消息', remark: '', sure: null };
if (isString(options)) {
thisOptions.message = options;
if (sure && isFunction(sure)) {
thisOptions.sure = sure;
}
}
else if (isJSON(options)) {
for (var key in options) {
if (key != 'type') {
thisOptions[key] = options[key];
}
}
}
var message = BoxConfigInstance.template.msgTip;
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 360;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.yes.callBack = thisOptions.sure;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
};
that.prompt = function () { };
that.loading = function (options) {
var thisOptions = { message: '正在处理,请稍等...', type: 'loading', title: '', remark: '', timeout: 0, callBack: null };
if (isString(options)) {
thisOptions.message = options;
}
else if (isJSON(options)) {
for (var key in options) {
if (key != 'type') {
thisOptions[key] = options[key];
}
}
}
var message = BoxConfigInstance.template.msgTip;
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 200;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.max.isShow = false;
BoxModelInstance.buttons.min.isShow = false;
BoxModelInstance.buttons.close.isShow = false;
BoxModelInstance.buttons.yes.isShow = false;
BoxModelInstance.buttons.no.isShow = false;
BoxModelInstance.buttons.cancel.isShow = false;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
if (BoxModelInstance.loadingThread) {
window.clearTimeout(BoxModelInstance.loadingThread);
BoxModelInstance.loadingThread = null;
}
if (thisOptions.timeout) {
BoxModelInstance.loadingThread = window.setTimeout(function () {
if (thisOptions.callBack) {
thisOptions.callBack.call(that);
}
close();
}, thisOptions.timeout);
}
};
that.confirm = function (options, sure, cancel) {
var thisOptions = { message: '[空]', type: 'help', title: '确认消息', remark: '', sure: null, cancel: null };
if (isString(options)) {
thisOptions.message = options;
if (sure && isFunction(sure)) {
thisOptions.sure = sure;
}
if (cancel && isFunction(cancel)) {
thisOptions.cancel = cancel;
}
}
else if (isJSON(options)) {
for (var key in options) {
if (key != 'type') {
thisOptions[key] = options[key];
}
}
}
var message = BoxConfigInstance.template.msgTip;
message = message.replace('#-TYPE-#', thisOptions.type).replace('#-MESSAGE-#', thisOptions.message).replace('#-REMARK-#', thisOptions.remark);
BoxModelInstance.width = 360;
BoxModelInstance.height = 90;
BoxModelInstance.title = thisOptions.title;
BoxModelInstance.content = message;
BoxModelInstance.buttons.yes.callBack = thisOptions.sure;
BoxModelInstance.buttons.cancel.callBack = thisOptions.cancel;
//创建按钮
renderButton();
//设置标题
renderTitle();
//设置内容
renderContent();
renderButtonKey();
show();
};
that.onYes = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onYes'] = fun;
}
return that;
};
that.onNo = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onNo'] = fun;
}
return that;
};
that.onCancel = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onCancel'] = fun;
}
return that;
};
that.onClose = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onClose'] = fun;
}
return that;
};
that.onShow = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onShow'] = fun;
}
return that;
};
that.onNext = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onNext'] = fun;
}
return that;
};
that.onPrev = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onPrev'] = fun;
}
return that;
};
that.onLoad = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onLoad'] = fun;
}
return that;
};
that.onDrag = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onDrag'] = fun;
}
return that;
};
that.onDragMove = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onDragMove'] = fun;
}
return that;
};
that.onDragEnd = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onDragEnd'] = fun;
}
return that;
};
that.onClick = function (fun) {
if (fun) {
BoxModelInstance.customEvent = BoxModelInstance.customEvent || {};
BoxModelInstance.customEvent['onClick'] = fun;
}
return that;
};
install();
};
});
var scripts = $('script');
var i = 0, length = scripts.length, scriptTarget, dataPath, src;
for (; i < length; i++) {
targetScript = scripts.eq(i);
dataPath = targetScript.attr('data-path');
dataParent = targetScript.attr('data-parent') || 'pages';
if (dataPath) {
src = '/global/script/' + dataParent + '/' + dataPath + '.js';
Module.Require(src, true);
}
}