UNPKG

iweb-tool

Version:
1,648 lines (1,487 loc) 657 kB
+function($) { //+ function($, exports) { 'use strict'; var IWEB_VERSION = "1.0.0" var IWEB_THEME = "i_theme" var IWEB_LOCALE = "i_locale" var IWEB_LANGUAGES = "i_languages" var IWEB_USERCODE = "usercode" var LOG_Level = "ill" var systemTimeZoneOffset = -480; //TODO 目前默认即取东八区 -60*8 = -480 var IWEB_CONTEXT_PATH = "contextpath" var iweb = { version: IWEB_VERSION }; if (!window.getCookie) { window.getCookie = function(sName) { var sRE = "(?:; )?" + sName + "=([^;]*);?"; var oRE = new RegExp(sRE); if (oRE.test(document.cookie)) { return decodeURIComponent(RegExp["$1"]); } else return null; }; } /** * 创建一个带壳的对象,防止外部修改 * @param {Object} proto */ window.createShellObject = function(proto) { var exf = function() {} exf.prototype = proto; return new exf(); }; // 导出到window对象中 //core context (function() { // 从Cookie中获取初始化信息 var environment = {} /** * client attributes */ var clientAttributes = {}; var sessionAttributes = {}; var maskerMeta = { 'float': { precision: 2 }, 'datetime': { format: 'yyyy-MM-dd hh:mm:ss', metaType: 'DateTimeFormatMeta', speratorSymbol: '-' }, 'time':{ format:'hh:mm:ss' }, 'date':{ format:'yyyy-MM-dd' }, 'currency':{ precision: 2, curSymbol: '¥' } } var fn = {} /** * 获取环境信息 * @return {environment} */ fn.getEnvironment = function() { return createShellObject(environment); } /** * 获取客户端参数对象 * @return {clientAttributes} */ fn.getClientAttributes = function() { var exf = function() {} return createShellObject(clientAttributes); } fn.setContextPath = function(contextPath) { return environment[IWEB_CONTEXT_PATH] = contextPath } fn.getContextPath = function(contextPath) { return environment[IWEB_CONTEXT_PATH] } /** * 设置客户端参数对象 * @param {Object} k 对象名称 * @param {Object} v 对象值(建议使用简单类型) */ fn.setClientAttribute = function(k, v) { clientAttributes[k] = v; } /** * 获取会话级参数对象 * @return {clientAttributes} */ fn.getSessionAttributes = function() { var exf = function() {} return createShellObject(sessionAttributes); } /** * 设置会话级参数对象 * @param {Object} k 对象名称 * @param {Object} v 对象值(建议使用简单类型) */ fn.setSessionAttribute = function(k, v) { sessionAttributes[k] = v; setCookie("ISES_" + k, v); } /** * 移除客户端参数 * @param {Object} k 对象名称 */ fn.removeClientAttribute = function(k) { clientAttributes[k] = null; execIgnoreError(function() { delete clientAttributes[k]; }) } /** * 获取根组件 */ fn.getRootComponent = function() { return this.rootComponet; } /** * 设置根组件 * @param {Object} component */ fn.setRootComponent = function(component) { this.rootComponet = component } /** * 获取主题名称 */ fn.getTheme = function() { return this.getEnvironment().theme } /** * 获取地区信息编码 */ fn.getLocale = function() { return this.getEnvironment().locale } /** * 获取多语信息 */ fn.getLanguages = function(){ return this.getEnvironment().languages } /** * 收集环境信息(包括客户端参数) * @return {Object} */ fn.collectEnvironment = function() { var _env = this.getEnvironment(); var _ses = this.getSessionAttributes(); for (var i in clientAttributes) { _ses[i] = clientAttributes[i]; } _env.clientAttributes = _ses; return _env } fn.changeTheme = function(theme) { environment.theme = theme; setCookie(IWEB_THEME, theme) $(document).trigger("themeChange"); } fn.changeLocale = function(locale) { environment.locale = locale; setCookie(IWEB_LOCALE, locale) $(document).trigger("localeChange"); } /** * 设置数据格式信息 * @param {String} type * @param {Object} meta */ fn.setMaskerMeta = function(type, meta) { if (!maskerMeta[type]) maskerMeta[type] = meta else{ if (typeof meta != 'object') maskerMeta[type] = meta else for (var key in meta){ maskerMeta[type][key] = meta[key] } } } fn.getMaskerMeta = function(type) { return $.extend({}, maskerMeta[type]) } /** * 注册系统时间偏移量 * @param {Object} offset */ fn.registerSystemTimeZoneOffset = function(offset) { systemTimeZoneOffset = offset; } /** * 获取系统时间偏移量 */ fn.getSystemTimeZoneOffset = function() { return systemTimeZoneOffset; }; // var device = { // Android: function() { // return /Android/i.test(navigator.userAgent); // }, // BlackBerry: function() { // return /BlackBerry/i.test(navigator.userAgent); // }, // iOS: function() { // return /iPhone|iPad|iPod/i.test(navigator.userAgent); // }, // Windows: function() { // return /IEMobile/i.test(navigator.userAgent); // }, // any: function() { // return (this.Android() || this.BlackBerry() || this.iOS() || this.Windows()); // }, // pc: function() { // return !this.any(); // }, // Screen: { // size: noop, // direction: noop // // } // } // fn.getDevice = function() { // return device; // } environment.theme = getCookie(IWEB_THEME) environment.locale = getCookie(IWEB_LOCALE) environment.languages = getCookie(IWEB_LANGUAGES) ? getCookie(IWEB_LANGUAGES).split(',') : ["ZH"] environment.timezoneOffset = (new Date()).getTimezoneOffset() environment.usercode = getCookie(IWEB_USERCODE) //init session attribute document.cookie.replace(/ISES_(\w*)=([^;]*);?/ig, function(a, b, c) { sessionAttributes[b] = c; }) var Core = function() {} Core.prototype = fn; iweb.Core = new Core(); })(); //console logger (function() { var consoleLog; var level = getCookie(IWEB_USERCODE) if (typeof Log4js != "undefined") { consoleLog = new Log4js.Logger("iweb"); consoleLog.setLevel(Log4js.Level.ERROR); var consoleAppender = new Log4js.ConsoleAppender(consoleLog, true); consoleLog.addAppender(consoleAppender); } else { consoleLog = { LEVEL_MAP: { "OFF": Number.MAX_VALUE, "ERROR": 40000, "WARN": 30000, "INFO": 20000, "DEBUG": 10000, "TRACE": 5000, "ALL": 1 }, level: 40000, setLevel: function(level) { if (level) { var l = this.LEVEL_MAP[level.toUpperCase()] if (l) { this.level = l; } } }, isDebugEnabled: function() { return (this.LEVEL_MAP.DEBUG >= this.level && console) }, isTraceEnabled: function() { return (this.LEVEL_MAP.TRACE >= this.level && console) }, isInfoEnabled: function() { return (this.LEVEL_MAP.INFO >= this.level && console) }, isWarnEnabled: function() { return (this.LEVEL_MAP.WARN >= this.level && console) }, isErrorEnabled: function() { return (this.LEVEL_MAP.ERROR >= this.level && console) }, debug: function() { if (this.isDebugEnabled()) { console.debug.call(console, arguments) } }, warn: function() { if (this.isWarnEnabled()) { console.debug.call(console, arguments) } }, info: function() { if (this.isInfoEnabled()) { console.debug.call(console, arguments) } }, trace: function() { if (this.isTraceEnabled()) { console.debug.call(console, arguments) } }, error: function() { if (this.isErrorEnabled()) { console.debug.call(console, arguments) } } } } consoleLog.setLevel(level); iweb.log = consoleLog; iweb.debugMode = false; })(); iweb.browser = { isIE: false, isFF: false, isOpera: false, isChrome: false, isSafari: false, isWebkit: false, isIE6: false, isIE7: false, isIE8: false, isIE8_CORE: false, isIE9: false, isIE9_CORE: false, isIE10: false, isIE10_ABOVE: false, isIE11: false, isIOS: false, isIphone: false, isIPAD: false, isStandard: false, version: 0 }; (function(){ var userAgent = navigator.userAgent, rMsie = /(msie\s|trident.*rv:)([\w.]+)/, rFirefox = /(firefox)\/([\w.]+)/, rOpera = /(opera).+version\/([\w.]+)/, rChrome = /(chrome)\/([\w.]+)/, rSafari = /version\/([\w.]+).*(safari)/, browser, version, ua = userAgent.toLowerCase(), s, browserMatch = null, match = rMsie.exec(ua); if (match != null) { browserMatch = { browser : "IE", version : match[2] || "0" }; } match = rFirefox.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rOpera.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rChrome.exec(ua); if (match != null) { browserMatch = { browser : match[1] || "", version : match[2] || "0" }; } match = rSafari.exec(ua); if (match != null) { browserMatch = { browser : match[2] || "", version : match[1] || "0" }; } if (match != null) { browserMatch = { browser : "", version : "0" }; } if (s=ua.match(/opera.([\d.]+)/)) { iweb.browser.isOpera = true; }else if(browserMatch.browser=="IE"&&browserMatch.version==11){ iweb.browser.isIE11 = true; iweb.browser.isIE = true; }else if (s=ua.match(/chrome\/([\d.]+)/)) { iweb.browser.isChrome = true; iweb.browser.isStandard = true; } else if (s=ua.match(/version\/([\d.]+).*safari/)) { iweb.browser.isSafari = true; iweb.browser.isStandard = true; } else if (s=ua.match(/gecko/)) { //add by licza : support XULRunner iweb.browser.isFF = true; iweb.browser.isStandard = true; } else if (s=ua.match(/msie ([\d.]+)/)) { iweb.browser.isIE = true; } else if (s=ua.match(/firefox\/([\d.]+)/)) { iweb.browser.isFF = true; iweb.browser.isStandard = true; } if (ua.match(/webkit\/([\d.]+)/)) { iweb.browser.isWebkit = true; } if (ua.match(/ipad/i)){ iweb.browser.isIOS = true; iweb.browser.isIPAD = true; iweb.browser.isStandard = true; } if (ua.match(/iphone/i)){ iweb.browser.isIOS = true; iweb.browser.isIphone = true; } iweb.browser.version = version ? (browserMatch.version ? browserMatch.version : 0) : 0; if (iweb.browser.isIE) { var intVersion = parseInt(iweb.browser.version); var mode = document.documentMode; if(mode == null){ if (intVersion == 6) { iweb.browser.isIE6 = true; } else if (intVersion == 7) { iweb.browser.isIE7 = true; } } else{ if(mode == 7){ iweb.browser.isIE7 = true; } else if (mode == 8) { iweb.browser.isIE8 = true; } else if (mode == 9) { iweb.browser.isIE9 = true; iweb.browser.isSTANDARD = true; } else if (mode == 10) { iweb.browser.isIE10 = true; iweb.browser.isSTANDARD = true; iweb.browser.isIE10_ABOVE = true; } else{ iweb.browser.isSTANDARD = true; } if (intVersion == 8) { iweb.browser.isIE8_CORE = true; } else if (intVersion == 9) { iweb.browser.isIE9_CORE = true; } else if(browserMatch.version==11){ iweb.browser.isIE11 = true; } else{ } } } })(); window.iweb = iweb; var noop = function() {} }($); + function($) { 'use strict'; /** * 字符串去掉左右空格 */ String.prototype.trim = function() { return this.replace(/^\s*(\b.*\b|)\s*$/, "$1"); }; /** * 字符串替换 */ String.prototype.replaceStr = function(strFind, strRemp) { var tab = this.split(strFind); return new String(tab.join(strRemp)); }; /** * 获得字符串的字节长度 */ String.prototype.lengthb = function() { // var str = this.replace(/[^\x800-\x10000]/g, "***"); var str = this.replace(/[^\x00-\xff]/g, "**"); return str.length; }; /** * 将AFindText全部替换为ARepText */ String.prototype.replaceAll = function(AFindText, ARepText) { //自定义String对象的方法 var raRegExp = new RegExp(AFindText, "g"); return this.replace(raRegExp, ARepText); }; /** * 按字节数截取字符串 例:"e我是d".nLen(4)将返回"e我" */ String.prototype.substrCH = function(nLen) { var i = 0; var j = 0; while (i < nLen && j < this.length) { // 循环检查制定的结束字符串位置是否存在中文字符 var charCode = this.charCodeAt(j); if (charCode > 256 && i == nLen - 1) { break; } // else if(charCode >= 0x800 && charCode <= 0x10000){ // i = i + 3; // } else if (charCode > 256) { // 返回指定下标字符编码,大于265表示是中文字符 i = i + 2; } //是中文字符,那计数增加2 else { i = i + 1; } //是英文字符,那计数增加1 j = j + 1; }; return this.substr(0, j); }; /** * 校验字符串是否以指定内容开始 */ String.prototype.startWith = function(strChild) { return this.indexOf(strChild) == 0; }; /** * 判断字符串是否以指定参数的字符串结尾 * * @param strChild */ String.prototype.endWith = function(strChild) { var index = this.indexOf(strChild); if (index == -1) return; else return index == this.length - strChild.length; }; String.prototype.format = function(data) { if (data != null) { var string = this; for (var key in data) { var reg = new RegExp('\\<\\#\\=' + key + '\\#\\>', 'gi'); string = string.replace(reg, data[key] ? (data[key] == 'null' ? "" : data[key]) : ""); } } return string; } function patch(element) { if (element.toString().length > 1) { return element.toString(); } else { return "0" + element.toString(); } } Date.prototype.format = function(format) { var year = this.getFullYear(), month = this.getMonth() + 1, day = this.getDate(), hour = this.getHours(), minute = this.getMinutes(), second = this.getSeconds(); format = format || "yyyy-MM-dd hh:mm:ss"; return format.replace(/yyyy/, year).replace(/yy/, year.toString().substr(2, 2)) .replace(/MM/, patch(month)).replace(/M/, month) .replace(/dd/, patch(day)).replace(/d/, day) .replace(/hh/, patch(hour)).replace(/h/, hour) .replace(/mm/, patch(minute)).replace(/m/, minute) .replace(/ss/, patch(second)).replace(/s/, second); }; /** * 获取AAAAMMJJ类型字符串 */ Date.prototype.getAAAAMMJJ = function() { //date du jour var jour = this.getDate(); if (jour < 10) (jour = "0" + jour); var mois = this.getMonth() + 1; if (mois < 10) (mois = "0" + mois); var annee = this.getYear(); return annee + "" + mois + "" + jour; }; /** * 获取YYYY-MM-DD类型字符串 */ Date.prototype.getFomatDate = function() { var year = this.getFullYear(); var month = this.getMonth() + 1; if (month < 10) month = "0" + month; var day = this.getDate(); if (day < 10) day = "0" + day; return year + "-" + month + "-" + day; }; /** * 获取YYYY-MM-DD HH:MM:SS类型字符串 */ Date.prototype.getFomatDateTime = function() { var year = this.getFullYear(); var month = this.getMonth() + 1; if (month < 10) month = "0" + month; var day = this.getDate(); if (day < 10) day = "0" + day; var hours = this.getHours(); if (hours < 10) hours = "0" + hours; var minutes = this.getMinutes(); if (minutes < 10) minutes = "0" + minutes; var seconds = this.getSeconds(); if (seconds < 10) seconds = "0" + seconds; return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; }; /** * 返回obj在数组中的位置 */ Array.prototype.indexOf = function(obj) { for (var i = 0; i < this.length; i++) { if (this[i] == obj) return i; } return -1; }; /** * 按照index remove */ Array.prototype.remove = function(index) { if (index < 0 || index > this.length) { alert("index out of bound"); return; } this.splice(index, 1); }; /** * 按照数组的元素remove */ Array.prototype.removeEle = function(ele) { for (var i = 0, count = this.length; i < count; i++) { if (this[i] == ele) { this.splice(i, 1); return; } } }; /** * 生成UUID */ Math.UUID = function() { return ((new Date()).getTime() + "").substr(9); }; String.UUID = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /** * 将指定值ele插入到index处 */ Array.prototype.insert = function(index, ele) { if (index < 0 || index > this.length) { alert("index out of bound"); return; } this.splice(index, 0, ele); }; /** * 得到和索引相对应的数组中的值 */ Array.prototype.values = function(indices) { if (indices == null) return null; var varr = new Array(); for (var i = 0; i < indices.length; i++) { varr.push(this[indices[i]]); } return varr; }; /** * 清空数组 */ Array.prototype.clear = function() { this.splice(0, this.length); }; window.getRequest = function(url) { if (!url) url = document.location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substring(url.indexOf("?") + 1); var strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }; window.setCookie = function(sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) sCookie += "; expires=" + oExpires.toGMTString(); if (sPath) sCookie += "; path=" + sPath; if (sDomain) sCookie += "; domain=" + sDomain; if (bSecure) sCookie += "; secure=" + bSecure; document.cookie = sCookie; }; window.getCookie = function(sName) { var sRE = "(?:; )?" + sName + "=([^;]*);?"; var oRE = new RegExp(sRE); if (oRE.test(document.cookie)) { return decodeURIComponent(RegExp["$1"]); } else return null; }; window.deleteCookie = function(sName, sPath, sDomain) { setCookie(sName, "", new Date(0), sPath, sDomain); }; window.execIgnoreError = function(a, b, c) { try { a.call(b, c); } catch (e) { //TODO handle the exception } } window.encodeBase64 = function(str){ var c1, c2, c3; var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var i = 0, len= str.length, string = ''; while (i < len){ c1 = str[i++] & 0xff; if (i == len){ string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt((c1 & 0x3) << 4); string += "=="; break; } c2 = str[i++]; if (i == len){ string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)); string += base64EncodeChars.charAt((c2 & 0xF) << 2); string += "="; break; } c3 = str[i++]; string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)); string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)); string += base64EncodeChars.charAt(c3 & 0x3F) } return string } $.getFunction = function(target, val){ if (!val || typeof val == 'function') return val if (typeof target[val] == 'function') return target[val] else if (typeof window[val] == 'function') return window[val] else if (val.indexOf('.') != -1){ var func = $.getJSObject(target, val) if (typeof func == 'function') return func func = $.getJSObject(window, val) if (typeof func == 'function') return func } return val } $.getJSObject = function(target, names) { if(!names) { return; } if (typeof names == 'object') return names var nameArr = names.split('.') var obj = target for (var i = 0; i < nameArr.length; i++) { obj = obj[nameArr[i]] if (!obj) return null } return obj } // 获取当前js文件的路径 window.getCurrentJsPath = function() { var doc = document, a = {}, expose = +new Date(), rExtractUri = /((?:http|https|file):\/\/.*?\/[^:]+)(?::\d+)?:\d+/, isLtIE8 = ('' + doc.querySelector).indexOf('[native code]') === -1; // FF,Chrome if (doc.currentScript){ return doc.currentScript.src; } var stack; try{ a.b(); } catch(e){ stack = e.fileName || e.sourceURL || e.stack || e.stacktrace; } // IE10 if (stack){ var absPath = rExtractUri.exec(stack)[1]; if (absPath){ return absPath; } } // IE5-9 for(var scripts = doc.scripts, i = scripts.length - 1, script; script = scripts[i--];){ if (script.className !== expose && script.readyState === 'interactive'){ script.className = expose; // if less than ie 8, must get abs path by getAttribute(src, 4) return isLtIE8 ? script.getAttribute('src', 4) : script.src; } } } }($); + function($) { "use strict"; if($.i18n || window.i18n) { var scriptPath = getCurrentJsPath(), _temp = scriptPath.substr(0, scriptPath.lastIndexOf('/')), __FOLDER__ = _temp.substr(0, _temp.lastIndexOf('/')) window.uuii18n = $.uuii18n = $.extend(true, {}, $.i18n || window.i18n) $.uuii18n.init({ postAsync: false, getAsync: false, fallbackLng: false, ns: { namespaces: ['uui-trans']}, resGetPath: __FOLDER__ + '/locales/__lng__/__ns__.json' }) } window.trans = $.trans = function(key, dftValue) { return $.i18n ? $.i18n.t('uui-trans:'+key) : dftValue } }($); /*====================================================== ************ mobile ************ ======================================================*/ !(function(){ if(!navigator.userAgent.match(/iPhone|iPod|Android|ios|iPad/i)){ return; } $.fn.extend({ transform: function(transform) { for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform; } return this; }, transition: function(duration) { if (typeof duration !== 'string') { duration = duration + 'ms'; } for (var i = 0; i < this.length; i++) { var elStyle = this[i].style; elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration; } return this; }, transitionEnd: function (callback) { var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'], i, j, dom = this; function fireCallBack(e) { /*jshint validthis:true */ if (e.target !== this) return; callback.call(this, e); for (i = 0; i < events.length; i++) { dom.off(events[i], fireCallBack); } } if (callback) { for (i = 0; i < events.length; i++) { dom.on(events[i], fireCallBack); } } return this; }}) $.app = {} var app=$.app; app.btn = true; app.openModal = function (modal) { //if(app.closebutton){ modal = $(modal); var isModal = modal.hasClass('modal'); if ($('.modal.modal-in:not(.modal-out)').length && app.params.modalStack && isModal) { app.modalStack.push(function () { app.openModal(modal); }); return; } var isPopover = modal.hasClass('popover'); var isPopup = modal.hasClass('popup'); var isLoginScreen = modal.hasClass('login-screen'); var isPickerModal = modal.hasClass('picker-modal'); if (isModal) { modal.show(); modal.css({ marginTop: - Math.round(modal.outerHeight() / 2) + 'px' }); } var overlay; if (!isLoginScreen && !isPickerModal) { if ($('.modal-overlay').length === 0 && !isPopup) { $('body').append('<div class="modal-overlay"></div>'); } if ($('.popup-overlay').length === 0 && isPopup) { $('body').append('<div class="popup-overlay"></div>'); } overlay = isPopup ? $('.popup-overlay') : $('.modal-overlay'); } //Make sure that styles are applied, trigger relayout; var clientLeft = modal[0].clientLeft; // Trugger open event modal.trigger('open'); // Picker modal body class if (isPickerModal) { $('body').addClass('with-picker-modal'); //$("html").addClass("hidden_srocll") } // Classes for transition in if (!isLoginScreen && !isPickerModal) overlay.addClass('modal-overlay-visible'); modal.removeClass('modal-out').addClass('modal-in').transitionEnd(function (e) { if (modal.hasClass('modal-out')) modal.trigger('closed'); else modal.trigger('opened'); }); // } return true; }; app.pickerModal = function (pickerModal, removeOnClose) { if (typeof removeOnClose === 'undefined') removeOnClose = false; if (typeof pickerModal === 'string' && pickerModal.indexOf('<') >= 0) { pickerModal = $(pickerModal); if (pickerModal.length > 0) { if (removeOnClose) pickerModal.addClass('remove-on-close'); $('body').append(pickerModal[0]); //$(top.document.body).append(pickerModal[0]); } else return false; //nothing found } pickerModal = $(pickerModal); if (pickerModal.length === 0) return false; // pickerModal.show(); // app.openModal(pickerModal); // pickerModal.hide(); // app.closeModal(pickerModal); return pickerModal[0]; }; app.closeModal = function (modal) { modal.find(".refer_input").blur(); modal.removeClass("refer_modal"); modal = $(modal || '.modal-in'); if (typeof modal !== 'undefined' && modal.length === 0) { return; } var isModal = modal.hasClass('modal'); var isPopover = modal.hasClass('popover'); var isPopup = modal.hasClass('popup'); var isLoginScreen = modal.hasClass('login-screen'); var isPickerModal = modal.hasClass('picker-modal'); var removeOnClose = modal.hasClass('remove-on-close'); var overlay = isPopup ? $('.popup-overlay') : $('.modal-overlay'); if (isPopup){ if (modal.length === $('.popup.modal-in').length) { overlay.removeClass('modal-overlay-visible'); } } else if (!isPickerModal) { overlay.removeClass('modal-overlay-visible'); } modal.trigger('close'); //取消消失动画 //modal.css("display","none") // Picker modal body class if (isPickerModal) { $('body').removeClass('with-picker-modal'); $("html").removeClass("hidden_srocll") $('body').addClass('picker-modal-closing'); } if (!isPopover) { modal.removeClass('modal-in').addClass('modal-out').transitionEnd(function (e) { if (modal.hasClass('modal-out')) modal.trigger('closed'); else modal.trigger('opened'); if (isPickerModal) { $('body').removeClass('picker-modal-closing'); $("html").removeClass("hidden_srocll") } if (isPopup || isLoginScreen || isPickerModal) { //modal.removeClass('modal-out').hide(); modal.removeClass('modal-out'); if (removeOnClose && modal.length > 0) { modal.remove(); } } else { modal.remove(); } }); if (isModal && app.params.modalStack) { app.modalStackClearQueue(); } } else { modal.removeClass('modal-in modal-out').trigger('closed').hide(); if (removeOnClose) { modal.remove(); } } $(".refer_select").removeClass("refer_select"); app.btn = true return true; }; app.accordionToggle = function (item) { item = $(item); if (item.length === 0) return; if (item.hasClass('accordion-item-expanded')) app.accordionClose(item); else app.accordionOpen(item); }; app.accordionOpen = function (item) { item = $(item); var list = item.parents('.accordion-list').eq(0); var content = item.children('.accordion-item-content'); if (content.length === 0) content = item.find('.accordion-item-content'); var expandedItem = list.length > 0 && item.parent().children('.accordion-item-expanded'); if (expandedItem.length > 0) { app.accordionClose(expandedItem); } content.css('height', content[0].scrollHeight + 'px').transitionEnd(function () { if (item.hasClass('accordion-item-expanded')) { content.transition(0); content.css('height', 'auto'); var clientLeft = content[0].clientLeft; content.transition(''); item.trigger('opened'); } else { content.css('height', ''); item.trigger('closed'); } }); item.trigger('open'); item.addClass('accordion-item-expanded'); }; app.accordionClose = function (item) { item = $(item); var content = item.children('.accordion-item-content'); if (content.length === 0) content = item.find('.accordion-item-content'); item.removeClass('accordion-item-expanded'); content.transition(0); content.css('height', content[0].scrollHeight + 'px'); // Relayout var clientLeft = content[0].clientLeft; // Close content.transition(''); content.css('height', '').transitionEnd(function () { if (item.hasClass('accordion-item-expanded')) { content.transition(0); content.css('height', 'auto'); var clientLeft = content[0].clientLeft; content.transition(''); item.trigger('opened'); } else { content.css('height', ''); item.trigger('closed'); } }); item.trigger('close'); }; app.support = (function () { var support = { touch: !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) }; // Export object return support; })(); app.mobile=(function () { var support = navigator.userAgent.match(/iPhone|iPod|Android|ios|iPad/i)?true:false // Export object return support; })(); $.getPickerArray = function(tmparray,type){ if(tmparray){ var tmp,tmpdd tmp = tmparray.split(' ') if(!tmp[1]) tmp[1] = "00:00" tmpdd = (tmp[0].split('-')).concat(tmp[1].split(':')) return tmpdd } } $.getTranslate = function (el, axis) { var matrix, curTransform, curStyle, transformMatrix; // automatic axis detection if (typeof axis === 'undefined') { axis = 'x'; } curStyle = window.getComputedStyle(el, null); if (window.WebKitCSSMatrix) { // Some old versions of Webkit choke when 'none' is passed; pass // empty string instead in this case transformMatrix = new WebKitCSSMatrix(curStyle.webkitTransform === 'none' ? '' : curStyle.webkitTransform); } else { transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,'); matrix = transformMatrix.toString().split(','); } if (axis === 'x') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41; //Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[12]); //Normal Browsers else curTransform = parseFloat(matrix[4]); } if (axis === 'y') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42; //Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[13]); //Normal Browsers else curTransform = parseFloat(matrix[5]); } return curTransform || 0; }; $.requestAnimationFrame = function (callback) { if (window.requestAnimationFrame) return window.requestAnimationFrame(callback); else if (window.webkitRequestAnimationFrame) return window.webkitRequestAnimationFrame(callback); else if (window.mozRequestAnimationFrame) return window.mozRequestAnimationFrame(callback); else { return window.setTimeout(callback, 1000 / 60); } }; $.cancelAnimationFrame = function (id) { if (window.cancelAnimationFrame) return window.cancelAnimationFrame(id); else if (window.webkitCancelAnimationFrame) return window.webkitCancelAnimationFrame(id); else if (window.mozCancelAnimationFrame) return window.mozCancelAnimationFrame(id); else { return window.clearTimeout(id); } }; $(document).on('touchend', '.refer_prev, .refer_next, .accordion-item-toggle, .close-picker', handleClicks); $(document).on('focus', '.refer_input', handleClicks); function handleClicks(e) { var clicked = $(this); if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) { var accordionItem = clicked.parent('.accordion-item'); if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item'); if (accordionItem.length === 0) accordionItem = clicked.parents('li'); app.accordionToggle(accordionItem); } if (clicked.hasClass('close-picker')) { var pickerToClose = $('.picker-modal.modal-in'); if (pickerToClose.length > 0) { app.closeModal(pickerToClose); } else { pickerToClose = $('.popover.modal-in .picker-modal'); if (pickerToClose.length > 0) { app.closeModal(pickerToClose.parents('.popover')); } } } if (clicked.hasClass('refer_prev')) { var tmpfield = $(".refer_select").parents(" fieldset[enable='true']") if(tmpfield.length > 0){ var tmpdate = tmpfield.prev("fieldset[enable='true']").find("[data-provide='datetimepicker'] div") if(tmpdate.length > 0){ tmpdate.triggerHandler("touchend"); return; } var tmpadd = tmpfield.prev("fieldset[enable='true']").find("input") if(tmpadd)tmpadd.triggerHandler("touchend") } } if (clicked.hasClass('refer_next')) { var tmpfield = $(".refer_select").parents("fieldset[enable='true']") if(tmpfield.length > 0){ var tmpdate = tmpfield.next("fieldset[enable='true']").find("[data-provide='datetimepicker'] div") if(tmpdate.length > 0 ){ tmpdate.triggerHandler("touchend"); return; } var tmpadd = tmpfield.next("fieldset[enable='true']").find("input") if(tmpadd)tmpadd.triggerHandler("toucend") } } if (clicked.hasClass('refer_input')) { e.preventDefault(); var pickerToHigh = $('.picker-modal.modal-in'); pickerToHigh.addClass("refer_modal") clicked.focus(); } } $(document).on("touchstart",function(e){ if ($(e.target).parents('.picker-modal').length === 0 ){ if($(".modal-out").length > 0 ) app.closeModal($(".modal-out")); if($(".modal-in").length > 0) app.closeModal($(".modal-in")); return; }else if($(e.target).parents('.est').length === 0 && $(e.target).parents('.toolbar-inner').length === 0 ){ e.preventDefault(); return; }; }) var Picker = function (params) { var p = this; var defaults = { updateValuesOnMomentum: false, updateValuesOnTouchmove: true, rotateEffect: false, momentumRatio: 7, freeMode: false, // Common settings scrollToInput: true, inputReadOnly: true, convertToPopover: true, onlyInPopover: false, toolbar: true, toolbarCloseText: 'DONE', toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left"><input style="margin-left:30px" class="refer_input" type="text"></div>' + '<div class="right">' + '<a href="#" class="link close-picker">{{closeText}}</a>' + '</div>' + '</div>' + '</div>' }; params = params || {}; for (var def in defaults) { if (typeof params[def] === 'undefined') { params[def] = defaults[def]; } } p.touchEvents = { start: app.support.touch ? 'touchstart' : 'mousedown', move: app.support.touch ? 'touchmove' : 'mousemove', end: app.support.touch ? 'touchend' : 'mouseup' }; p.params = params; p.cols = []; p.initialized = false; // Inline flag p.inline = p.params.container ? true : false; // 3D Transforms origin bug, only on safari var originBug = true; //app.device.ios || (navigator.userAgent.toLowerCase().indexOf('safari') >= 0 && navigator.userAgent.toLowerCase().indexOf('chrome') < 0) && !app.device.android; // Should be converted to popover function isPopover() { var toPopover = false; if (!p.params.convertToPopover && !p.params.onlyInPopover) return toPopover; if (!p.inline && p.params.input) { if (p.params.onlyInPopover) toPopover = true; else { if (app.device.ios) { toPopover = app.device.ipad ? true : false; } else { if ($(window).width() >= 768) toPopover = true; } } } return toPopover; } function inPopover() { if (p.opened && p.container && p.container.length > 0 && p.container.parents('.popover').length > 0) return true; else return false; } // Value p.setValue = function (arrValues, transition) { var valueIndex = 0; for (var i = 0; i < p.cols.length; i++) { if (p.cols[i] && !p.cols[i].divider) { p.cols[i].setValue(arrValues[valueIndex], transition); valueIndex++; } } }; p.updateValue = function () { var newValue = []; var newDisplayValue = []; for (var i = 0; i < p.cols.length; i++) { if (!p.cols[i].divider) { newValue.push(p.cols[i].value); newDisplayValue.push(p.cols[i].displayValue); } } if (newValue.indexOf(undefined) >= 0) { return; } p.value = newValue; p.displayValue = newDisplayValue; if (p.params.onChange) { p.params.onChange(p, p.value, p.displayValue); } if (p.input && p.input.length > 0) { $(p.input).find("input").data("dd",p.value).val(p.params.formatValue ? p.params.formatValue(p, p.value, p.displayValue) : p.value.join(' ')); $(p.input).find("input").trigger('picker_close'); } }; // Columns Handlers p.initPickerCol = function (colElement, updateItems) { var colContainer = $(colElement); var colIndex = colContainer.index(); var col = p.cols[colIndex]; if (col.divider) return; col.container = colContainer; col.wrapper = col.container.find('.picker-items-col-wrapper'); col.items = col.wrapper.find('.picker-item'); var i, j; var wrapperHeight, itemHeight, itemsHeight, minTranslate, maxTranslate; col.replaceValues = function (values, displayValues) { col.destroyEvents(); col.values = values; col.displayValues = displayValues; var newItemsHTML = p.columnHTML(col, true); col.wrapper.html(newItemsHTML); col.items = col.wrapper.find('.picker-item'); col.calcSize(); col.setValue(col.values[0], 0, true); col.initEvents(); }; col.calcSize = function () { if (p.params.rotateEffect) { col.container.removeClass('picker-items-col-absolute'); if (!col.width) col.container.css({width:''}); } var colWidth, colHeight; colWidth = 0; colHeight = col.container[0].offsetHeight; wrapperHeight = col.wrapper[0].offsetHeight; itemHeight = col.items[0].offsetHeight; itemsHeight = itemHeight * col.items.length; minTranslate = colHeight / 2 - itemsHeight + itemHeight / 2; maxTranslate = colHeight / 2 - itemHeight / 2; if (col.width) { colWidth = col.width; if (parseInt(colWidth, 10) === colWidth) colWidth = colWidth + 'px'; col.container.css({width: colWidth}); } if (p.params.rotateEffect) { if (!col.width) { col.items.each(function () { var item = $(this); item.css({width:'auto'}); colWidth = Math.max(colWidth, item[0].offsetWidth); item.css({width:''}); }); col.container.css({width: (colWidth + 2) + 'px'}); } col.container.addClass('picker-items-col-absolute'); } }; col.calcSize(); col.wrapper.transform('translate3d(0,' + maxTranslate + 'px,0)').transition(0); var activeIndex = 0; var animationFrameId; // Set Value Function col.setValue = function (newValue, transition, valueCallbacks) { if (typeof transition === 'undefined') transition = ''; var newActiveIndex = col.wrapper.find('.picker-item[data-picker-value="' + newValue + '"]').index(); if(typeof newActiveIndex === 'undefined' || newActiveIndex === -1) { return; } var newTranslate = -newActiveIndex * itemHeight + maxTranslate; // Update wrapper col.wrapper.transition(transition); col.wrapper.transform('translate3d(0,' + (newTranslate) + 'px,0)'); // Watch items if (p.params.updateValuesOnMomentum && col.activeIndex && col.activeIndex !== newActiveIndex ) { $.cancelAnimationFrame(animationFrameId); col.wrapper.transitionEnd(function(){ $.cancelAnimationFrame(animationFrameId); }); updateDuringScroll(); } // Update items col.updateItems(newActiveIndex, newTranslate, transition, valueCallbacks); }; col.updateItems = function (activeIndex, translate, transition, valueCallbacks) { if (typeof translate === 'undefined') { translate = $.getTranslate(col.wrapper[0], 'y'); } if(typeof activeIndex === 'undefined') activeIndex = -Math.round((translate - maxTranslate)/itemHeight); if (activeIndex < 0) activeIndex = 0; if (activeIndex >= col.items.length) activeIndex = col.items.length - 1; var previousActiveIndex = col.activeIndex; col.activeIndex = activeIndex; col.wrapper.find('.picker-selected, .picker-after-selected, .picker-before-selected').removeClass('picker-selected picker-after-selected picker-before-selected'); col.items.transition(transition); var selectedItem = col.items.eq(activeIndex).addClass('picker-selected').transform(''); var prevItems = selectedItem.prevAll().addClass('picker-before-selected'); var nextItems = selectedItem.nextAll().addClass('picker-after-selected'); if (valueCallbacks || typeof valueCallbacks === 'undefined') { // Update values col.value = selectedItem.attr('data-picker-value'); col.displayValue = col.displayValues ? col.displayValues[activeIndex] : col.value; // On change callback if (previousActiveIndex !== activeIndex) { if (col.onChange) { col.onChange(p, col.value, col.displayValue); } p.updateValue(); } } // Set 3D rotate effect if (!p.params.rotateEffect) { return; } var percentage = (translate - (Math.floor((translate - maxTranslate)/itemHeight) * itemHeight + maxTranslate)) / itemHeight; col.items.each(function () { var item = $(this); var itemOffsetTop = item.index() * itemHeight; var translateOffset = maxTranslate - translate; var itemOffset = itemOffsetTop - translateOffset; var percentage = itemOffset / itemHeight; var itemsFit = Math.ceil(col.height / itemHeight / 2) + 1; var angle = (-18*percentage); if (angle > 180) angle = 180; if (angle < -180) angle = -180; // Far class if (Math.abs(percentage) > itemsFit) item.addClass('picker-item-far'); else item.removeClass('picker-item-far'); // Set transform item.transform('translate3d(0, ' + (-translate + maxTranslate) + 'px, ' + (originBug ? -110 : 0) + 'px) rotateX(' + angle + 'deg)'); }); }; function updateDuringScroll() { animationFrameId = $.requestAnimationFrame(function () { col.updateItems(undefined, undefined, 0); updateDuringScroll(); }); } // Update items on init if (updateItems) col.updateItems(0, maxTranslate, 0); var allowItemClick = true; var isTouched, isMoved, touchStartY, touchCurrentY, touchStartTime, touchEndTime, startTranslate, returnTo, currentTranslate, prevTranslate, velocityTranslate, velocityTime; function handleTouchStart (e) { if (isMoved || isTouched) return; e.preventDefault(); isTouched = true; touchStartY = touchCurrentY = e.type === 'touchstart' ? e.originalEvent.targetTouches[0].pageY : e.pageY; touchStartTime = (new Date()).getTime(); allowItemClick = true; startTranslate = currentTranslate = $.getTranslate(col.wrapper[0], 'y'); } function handleTouchMove (e) { if (!isTouched) return; e.preventDefault(); allowItemClick = false; touchCurrentY = e.type === 'touchmove' ? e.originalEvent.targetTouches[0].pageY : e.pageY; if (!isMoved) { // First move $.cancelAnimationFrame(animationFrameId); isMoved = true; startTranslate = currentTranslate = $.getTranslate(col.wrapper[0], 'y'); col.wrapper.transition(0); } e.preventDefault(); var diff = touchCurrentY - touchStartY; currentTranslate = startTranslate + diff; returnTo = undefined; // Normalize translate if (currentTranslate < minTranslate) { currentTranslate = minTranslate - Math.pow(minTranslate - currentTranslate, 0.8); returnTo = 'min'; } if (currentTranslate > maxTranslate) { currentTranslate = maxTranslate + Math.pow(currentTranslate - maxTranslate, 0.8); returnTo = 'max'; } // Transform wrapper col.wrapper.transform('translate3d(0,' + cur