1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433 |
- /*!
- * =====================================================
- * Mui v3.7.2 (http://dev.dcloud.net.cn/mui)
- * =====================================================
- */
- /**
- * MUI核心JS
- * @type _L4.$|Function
- */
- var mui = (function(document, undefined) {
- var readyRE = /complete|loaded|interactive/;
- var idSelectorRE = /^#([\w-]+)$/;
- var classSelectorRE = /^\.([\w-]+)$/;
- var tagSelectorRE = /^[\w-]+$/;
- var translateRE = /translate(?:3d)?\((.+?)\)/;
- var translateMatrixRE = /matrix(3d)?\((.+?)\)/;
- var $ = function(selector, context) {
- context = context || document;
- if (!selector)
- return wrap();
- if (typeof selector === 'object')
- if ($.isArrayLike(selector)) {
- return wrap($.slice.call(selector), null);
- } else {
- return wrap([selector], null);
- }
- if (typeof selector === 'function')
- return $.ready(selector);
- if (typeof selector === 'string') {
- try {
- selector = selector.trim();
- if (idSelectorRE.test(selector)) {
- var found = document.getElementById(RegExp.$1);
- return wrap(found ? [found] : []);
- }
- return wrap($.qsa(selector, context), selector);
- } catch (e) {}
- }
- return wrap();
- };
- var wrap = function(dom, selector) {
- dom = dom || [];
- Object.setPrototypeOf(dom, $.fn);
- dom.selector = selector || '';
- return dom;
- };
- $.uuid = 0;
- $.data = {};
- /**
- * extend(simple)
- * @param {type} target
- * @param {type} source
- * @param {type} deep
- * @returns {unresolved}
- */
- $.extend = function() { //from jquery2
- var options, name, src, copy, copyIsArray, clone,
- target = arguments[0] || {},
- i = 1,
- length = arguments.length,
- deep = false;
- if (typeof target === "boolean") {
- deep = target;
- target = arguments[i] || {};
- i++;
- }
- if (typeof target !== "object" && !$.isFunction(target)) {
- target = {};
- }
- if (i === length) {
- target = this;
- i--;
- }
- for (; i < length; i++) {
- if ((options = arguments[i]) != null) {
- for (name in options) {
- src = target[name];
- copy = options[name];
- if (target === copy) {
- continue;
- }
- if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {
- if (copyIsArray) {
- copyIsArray = false;
- clone = src && $.isArray(src) ? src : [];
- } else {
- clone = src && $.isPlainObject(src) ? src : {};
- }
- target[name] = $.extend(deep, clone, copy);
- } else if (copy !== undefined) {
- target[name] = copy;
- }
- }
- }
- }
- return target;
- };
- /**
- * mui noop(function)
- */
- $.noop = function() {};
- /**
- * mui slice(array)
- */
- $.slice = [].slice;
- /**
- * mui filter(array)
- */
- $.filter = [].filter;
- $.type = function(obj) {
- return obj == null ? String(obj) : class2type[{}.toString.call(obj)] || "object";
- };
- /**
- * mui isArray
- */
- $.isArray = Array.isArray ||
- function(object) {
- return object instanceof Array;
- };
- /**
- * mui isArrayLike
- * @param {Object} obj
- */
- $.isArrayLike = function(obj) {
- var length = !!obj && "length" in obj && obj.length;
- var type = $.type(obj);
- if (type === "function" || $.isWindow(obj)) {
- return false;
- }
- return type === "array" || length === 0 ||
- typeof length === "number" && length > 0 && (length - 1) in obj;
- };
- /**
- * mui isWindow(需考虑obj为undefined的情况)
- */
- $.isWindow = function(obj) {
- return obj != null && obj === obj.window;
- };
- /**
- * mui isObject
- */
- $.isObject = function(obj) {
- return $.type(obj) === "object";
- };
- /**
- * mui isPlainObject
- */
- $.isPlainObject = function(obj) {
- return $.isObject(obj) && !$.isWindow(obj) && Object.getPrototypeOf(obj) === Object.prototype;
- };
- /**
- * mui isEmptyObject
- * @param {Object} o
- */
- $.isEmptyObject = function(o) {
- for (var p in o) {
- if (p !== undefined) {
- return false;
- }
- }
- return true;
- };
- /**
- * mui isFunction
- */
- $.isFunction = function(value) {
- return $.type(value) === "function";
- };
- /**
- * mui querySelectorAll
- * @param {type} selector
- * @param {type} context
- * @returns {Array}
- */
- $.qsa = function(selector, context) {
- context = context || document;
- return $.slice.call(classSelectorRE.test(selector) ? context.getElementsByClassName(RegExp.$1) : tagSelectorRE.test(selector) ? context.getElementsByTagName(selector) : context.querySelectorAll(selector));
- };
- /**
- * ready(DOMContentLoaded)
- * @param {type} callback
- * @returns {_L6.$}
- */
- $.ready = function(callback) {
- if (readyRE.test(document.readyState)) {
- callback($);
- } else {
- document.addEventListener('DOMContentLoaded', function() {
- callback($);
- }, false);
- }
- return this;
- };
- /**
- * 将 fn 缓存一段时间后, 再被调用执行
- * 此方法为了避免在 ms 段时间内, 执行 fn 多次. 常用于 resize , scroll , mousemove 等连续性事件中;
- * 当 ms 设置为 -1, 表示立即执行 fn, 即和直接调用 fn 一样;
- * 调用返回函数的 stop 停止最后一次的 buffer 效果
- * @param {Object} fn
- * @param {Object} ms
- * @param {Object} context
- */
- $.buffer = function(fn, ms, context) {
- var timer;
- var lastStart = 0;
- var lastEnd = 0;
- var ms = ms || 150;
- function run() {
- if (timer) {
- timer.cancel();
- timer = 0;
- }
- lastStart = $.now();
- fn.apply(context || this, arguments);
- lastEnd = $.now();
- }
- return $.extend(function() {
- if (
- (!lastStart) || // 从未运行过
- (lastEnd >= lastStart && $.now() - lastEnd > ms) || // 上次运行成功后已经超过ms毫秒
- (lastEnd < lastStart && $.now() - lastStart > ms * 8) // 上次运行或未完成,后8*ms毫秒
- ) {
- run.apply(this, arguments);
- } else {
- if (timer) {
- timer.cancel();
- }
- timer = $.later(run, ms, null, $.slice.call(arguments));
- }
- }, {
- stop: function() {
- if (timer) {
- timer.cancel();
- timer = 0;
- }
- }
- });
- };
- /**
- * each
- * @param {type} elements
- * @param {type} callback
- * @returns {_L8.$}
- */
- $.each = function(elements, callback, hasOwnProperty) {
- if (!elements) {
- return this;
- }
- if (typeof elements.length === 'number') {
- [].every.call(elements, function(el, idx) {
- return callback.call(el, idx, el) !== false;
- });
- } else {
- for (var key in elements) {
- if (hasOwnProperty) {
- if (elements.hasOwnProperty(key)) {
- if (callback.call(elements[key], key, elements[key]) === false) return elements;
- }
- } else {
- if (callback.call(elements[key], key, elements[key]) === false) return elements;
- }
- }
- }
- return this;
- };
- $.focus = function(element) {
- if ($.os.ios) {
- setTimeout(function() {
- element.focus();
- }, 10);
- } else {
- element.focus();
- }
- };
- /**
- * trigger event
- * @param {type} element
- * @param {type} eventType
- * @param {type} eventData
- * @returns {_L8.$}
- */
- $.trigger = function(element, eventType, eventData) {
- element.dispatchEvent(new CustomEvent(eventType, {
- detail: eventData,
- bubbles: true,
- cancelable: true
- }));
- return this;
- };
- /**
- * getStyles
- * @param {type} element
- * @param {type} property
- * @returns {styles}
- */
- $.getStyles = function(element, property) {
- var styles = element.ownerDocument.defaultView.getComputedStyle(element, null);
- if (property) {
- return styles.getPropertyValue(property) || styles[property];
- }
- return styles;
- };
- /**
- * parseTranslate
- * @param {type} translateString
- * @param {type} position
- * @returns {Object}
- */
- $.parseTranslate = function(translateString, position) {
- var result = translateString.match(translateRE || '');
- if (!result || !result[1]) {
- result = ['', '0,0,0'];
- }
- result = result[1].split(",");
- result = {
- x: parseFloat(result[0]),
- y: parseFloat(result[1]),
- z: parseFloat(result[2])
- };
- if (position && result.hasOwnProperty(position)) {
- return result[position];
- }
- return result;
- };
- /**
- * parseTranslateMatrix
- * @param {type} translateString
- * @param {type} position
- * @returns {Object}
- */
- $.parseTranslateMatrix = function(translateString, position) {
- var matrix = translateString.match(translateMatrixRE);
- var is3D = matrix && matrix[1];
- if (matrix) {
- matrix = matrix[2].split(",");
- if (is3D === "3d")
- matrix = matrix.slice(12, 15);
- else {
- matrix.push(0);
- matrix = matrix.slice(4, 7);
- }
- } else {
- matrix = [0, 0, 0];
- }
- var result = {
- x: parseFloat(matrix[0]),
- y: parseFloat(matrix[1]),
- z: parseFloat(matrix[2])
- };
- if (position && result.hasOwnProperty(position)) {
- return result[position];
- }
- return result;
- };
- $.hooks = {};
- $.addAction = function(type, hook) {
- var hooks = $.hooks[type];
- if (!hooks) {
- hooks = [];
- }
- hook.index = hook.index || 1000;
- hooks.push(hook);
- hooks.sort(function(a, b) {
- return a.index - b.index;
- });
- $.hooks[type] = hooks;
- return $.hooks[type];
- };
- $.doAction = function(type, callback) {
- if ($.isFunction(callback)) { //指定了callback
- $.each($.hooks[type], callback);
- } else { //未指定callback,直接执行
- $.each($.hooks[type], function(index, hook) {
- return !hook.handle();
- });
- }
- };
- /**
- * setTimeout封装
- * @param {Object} fn
- * @param {Object} when
- * @param {Object} context
- * @param {Object} data
- */
- $.later = function(fn, when, context, data) {
- when = when || 0;
- var m = fn;
- var d = data;
- var f;
- var r;
- if (typeof fn === 'string') {
- m = context[fn];
- }
- f = function() {
- m.apply(context, $.isArray(d) ? d : [d]);
- };
- r = setTimeout(f, when);
- return {
- id: r,
- cancel: function() {
- clearTimeout(r);
- }
- };
- };
- $.now = Date.now || function() {
- return +new Date();
- };
- var class2type = {};
- $.each(['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Object', 'Error'], function(i, name) {
- class2type["[object " + name + "]"] = name.toLowerCase();
- });
- if (window.JSON) {
- $.parseJSON = JSON.parse;
- }
- /**
- * $.fn
- */
- $.fn = {
- each: function(callback) {
- [].every.call(this, function(el, idx) {
- return callback.call(el, idx, el) !== false;
- });
- return this;
- }
- };
- /**
- * 兼容 AMD 模块
- **/
- if (typeof define === 'function' && define.amd) {
- define('mui', [], function() {
- return $;
- });
- }
- return $;
- })(document);
- //window.mui = mui;
- //'$' in window || (window.$ = mui);
- /**
- * $.os
- * @param {type} $
- * @returns {undefined}
- */
- (function($, window) {
- function detect(ua) {
- this.os = {};
- var funcs = [
- function() { //wechat
- var wechat = ua.match(/(MicroMessenger)\/([\d\.]+)/i);
- if (wechat) { //wechat
- this.os.wechat = {
- version: wechat[2].replace(/_/g, '.')
- };
- }
- return false;
- },
- function() { //android
- var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
- if (android) {
- this.os.android = true;
- this.os.version = android[2];
- this.os.isBadAndroid = !(/Chrome\/\d/.test(window.navigator.appVersion));
- }
- return this.os.android === true;
- },
- function() { //ios
- var iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/);
- if (iphone) { //iphone
- this.os.ios = this.os.iphone = true;
- this.os.version = iphone[2].replace(/_/g, '.');
- } else {
- var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
- if (ipad) { //ipad
- this.os.ios = this.os.ipad = true;
- this.os.version = ipad[2].replace(/_/g, '.');
- }
- }
- return this.os.ios === true;
- }
- ];
- [].every.call(funcs, function(func) {
- return !func.call($);
- });
- }
- detect.call($, navigator.userAgent);
- })(mui, window);
- /**
- * $.os.plus
- * @param {type} $
- * @returns {undefined}
- */
- (function($, document) {
- function detect(ua) {
- this.os = this.os || {};
- var plus = ua.match(/Html5Plus/i); //TODO 5\+Browser?
- if (plus) {
- this.os.plus = true;
- $(function() {
- document.body.classList.add('mui-plus');
- });
- if (ua.match(/StreamApp/i)) { //TODO 最好有流应用自己的标识
- this.os.stream = true;
- $(function() {
- document.body.classList.add('mui-plus-stream');
- });
- }
- }
- }
- detect.call($, navigator.userAgent);
- })(mui, document);
- /**
- * 仅提供简单的on,off(仅支持事件委托,不支持当前元素绑定,当前元素绑定请直接使用addEventListener,removeEventListener)
- * @param {Object} $
- */
- (function($) {
- if ('ontouchstart' in window) {
- $.isTouchable = true;
- $.EVENT_START = 'touchstart';
- $.EVENT_MOVE = 'touchmove';
- $.EVENT_END = 'touchend';
- } else {
- $.isTouchable = false;
- $.EVENT_START = 'mousedown';
- $.EVENT_MOVE = 'mousemove';
- $.EVENT_END = 'mouseup';
- }
- $.EVENT_CANCEL = 'touchcancel';
- $.EVENT_CLICK = 'click';
- var _mid = 1;
- var delegates = {};
- //需要wrap的函数
- var eventMethods = {
- preventDefault: 'isDefaultPrevented',
- stopImmediatePropagation: 'isImmediatePropagationStopped',
- stopPropagation: 'isPropagationStopped'
- };
- //默认true返回函数
- var returnTrue = function() {
- return true
- };
- //默认false返回函数
- var returnFalse = function() {
- return false
- };
- //wrap浏览器事件
- var compatible = function(event, target) {
- if (!event.detail) {
- event.detail = {
- currentTarget: target
- };
- } else {
- event.detail.currentTarget = target;
- }
- $.each(eventMethods, function(name, predicate) {
- var sourceMethod = event[name];
- event[name] = function() {
- this[predicate] = returnTrue;
- return sourceMethod && sourceMethod.apply(event, arguments)
- }
- event[predicate] = returnFalse;
- }, true);
- return event;
- };
- //简单的wrap对象_mid
- var mid = function(obj) {
- return obj && (obj._mid || (obj._mid = _mid++));
- };
- //事件委托对象绑定的事件回调列表
- var delegateFns = {};
- //返回事件委托的wrap事件回调
- var delegateFn = function(element, event, selector, callback) {
- return function(e) {
- //same event
- var callbackObjs = delegates[element._mid][event];
- var handlerQueue = [];
- var target = e.target;
- var selectorAlls = {};
- for (; target && target !== document; target = target.parentNode) {
- if (target === element) {
- break;
- }
- if (~['click', 'tap', 'doubletap', 'longtap', 'hold'].indexOf(event) && (target.disabled || target.classList.contains('mui-disabled'))) {
- break;
- }
- var matches = {};
- $.each(callbackObjs, function(selector, callbacks) { //same selector
- selectorAlls[selector] || (selectorAlls[selector] = $.qsa(selector, element));
- if (selectorAlls[selector] && ~(selectorAlls[selector]).indexOf(target)) {
- if (!matches[selector]) {
- matches[selector] = callbacks;
- }
- }
- }, true);
- if (!$.isEmptyObject(matches)) {
- handlerQueue.push({
- element: target,
- handlers: matches
- });
- }
- }
- selectorAlls = null;
- e = compatible(e); //compatible event
- $.each(handlerQueue, function(index, handler) {
- target = handler.element;
- var tagName = target.tagName;
- if (event === 'tap' && (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && tagName !== 'SELECT')) {
- e.preventDefault();
- e.detail && e.detail.gesture && e.detail.gesture.preventDefault();
- }
- $.each(handler.handlers, function(index, handler) {
- $.each(handler, function(index, callback) {
- if (callback.call(target, e) === false) {
- e.preventDefault();
- e.stopPropagation();
- }
- }, true);
- }, true)
- if (e.isPropagationStopped()) {
- return false;
- }
- }, true);
- };
- };
- var findDelegateFn = function(element, event) {
- var delegateCallbacks = delegateFns[mid(element)];
- var result = [];
- if (delegateCallbacks) {
- result = [];
- if (event) {
- var filterFn = function(fn) {
- return fn.type === event;
- }
- return delegateCallbacks.filter(filterFn);
- } else {
- result = delegateCallbacks;
- }
- }
- return result;
- };
- var preventDefaultException = /^(INPUT|TEXTAREA|BUTTON|SELECT)$/;
- /**
- * mui delegate events
- * @param {type} event
- * @param {type} selector
- * @param {type} callback
- * @returns {undefined}
- */
- $.fn.on = function(event, selector, callback) { //仅支持简单的事件委托,主要是tap事件使用,类似mouse,focus之类暂不封装支持
- return this.each(function() {
- var element = this;
- mid(element);
- mid(callback);
- var isAddEventListener = false;
- var delegateEvents = delegates[element._mid] || (delegates[element._mid] = {});
- var delegateCallbackObjs = delegateEvents[event] || ((delegateEvents[event] = {}));
- if ($.isEmptyObject(delegateCallbackObjs)) {
- isAddEventListener = true;
- }
- var delegateCallbacks = delegateCallbackObjs[selector] || (delegateCallbackObjs[selector] = []);
- delegateCallbacks.push(callback);
- if (isAddEventListener) {
- var delegateFnArray = delegateFns[mid(element)];
- if (!delegateFnArray) {
- delegateFnArray = [];
- }
- var delegateCallback = delegateFn(element, event, selector, callback);
- delegateFnArray.push(delegateCallback);
- delegateCallback.i = delegateFnArray.length - 1;
- delegateCallback.type = event;
- delegateFns[mid(element)] = delegateFnArray;
- element.addEventListener(event, delegateCallback);
- if (event === 'tap') { //TODO 需要找个更好的解决方案
- element.addEventListener('click', function(e) {
- if (e.target) {
- var tagName = e.target.tagName;
- if (!preventDefaultException.test(tagName)) {
- if (tagName === 'A') {
- var href = e.target.href;
- if (!(href && ~href.indexOf('tel:'))) {
- e.preventDefault();
- }
- } else {
- e.preventDefault();
- }
- }
- }
- });
- }
- }
- });
- };
- $.fn.off = function(event, selector, callback) {
- return this.each(function() {
- var _mid = mid(this);
- if (!event) { //mui(selector).off();
- delegates[_mid] && delete delegates[_mid];
- } else if (!selector) { //mui(selector).off(event);
- delegates[_mid] && delete delegates[_mid][event];
- } else if (!callback) { //mui(selector).off(event,selector);
- delegates[_mid] && delegates[_mid][event] && delete delegates[_mid][event][selector];
- } else { //mui(selector).off(event,selector,callback);
- var delegateCallbacks = delegates[_mid] && delegates[_mid][event] && delegates[_mid][event][selector];
- $.each(delegateCallbacks, function(index, delegateCallback) {
- if (mid(delegateCallback) === mid(callback)) {
- delegateCallbacks.splice(index, 1);
- return false;
- }
- }, true);
- }
- if (delegates[_mid]) {
- //如果off掉了所有当前element的指定的event事件,则remove掉当前element的delegate回调
- if ((!delegates[_mid][event] || $.isEmptyObject(delegates[_mid][event]))) {
- findDelegateFn(this, event).forEach(function(fn) {
- this.removeEventListener(fn.type, fn);
- delete delegateFns[_mid][fn.i];
- }.bind(this));
- }
- } else {
- //如果delegates[_mid]已不存在,删除所有
- findDelegateFn(this).forEach(function(fn) {
- this.removeEventListener(fn.type, fn);
- delete delegateFns[_mid][fn.i];
- }.bind(this));
- }
- });
- };
- })(mui);
- /**
- * mui target(action>popover>modal>tab>toggle)
- */
- (function($, window, document) {
- /**
- * targets
- */
- $.targets = {};
- /**
- * target handles
- */
- $.targetHandles = [];
- /**
- * register target
- * @param {type} target
- * @returns {$.targets}
- */
- $.registerTarget = function(target) {
- target.index = target.index || 1000;
- $.targetHandles.push(target);
- $.targetHandles.sort(function(a, b) {
- return a.index - b.index;
- });
- return $.targetHandles;
- };
- window.addEventListener($.EVENT_START, function(event) {
- var target = event.target;
- var founds = {};
- for (; target && target !== document; target = target.parentNode) {
- var isFound = false;
- $.each($.targetHandles, function(index, targetHandle) {
- var name = targetHandle.name;
- if (!isFound && !founds[name] && targetHandle.hasOwnProperty('handle')) {
- $.targets[name] = targetHandle.handle(event, target);
- if ($.targets[name]) {
- founds[name] = true;
- if (targetHandle.isContinue !== true) {
- isFound = true;
- }
- }
- } else {
- if (!founds[name]) {
- if (targetHandle.isReset !== false)
- $.targets[name] = false;
- }
- }
- });
- if (isFound) {
- break;
- }
- }
- });
- window.addEventListener('click', function(event) { //解决touch与click的target不一致的问题(比如链接边缘点击时,touch的target为html,而click的target为A)
- var target = event.target;
- var isFound = false;
- for (; target && target !== document; target = target.parentNode) {
- if (target.tagName === 'A') {
- $.each($.targetHandles, function(index, targetHandle) {
- var name = targetHandle.name;
- if (targetHandle.hasOwnProperty('handle')) {
- if (targetHandle.handle(event, target)) {
- isFound = true;
- event.preventDefault();
- return false;
- }
- }
- });
- if (isFound) {
- break;
- }
- }
- }
- });
- })(mui, window, document);
- /**
- * fixed trim
- * @param {type} undefined
- * @returns {undefined}
- */
- (function(undefined) {
- if (String.prototype.trim === undefined) { // fix for iOS 3.2
- String.prototype.trim = function() {
- return this.replace(/^\s+|\s+$/g, '');
- };
- }
- Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
- obj['__proto__'] = proto;
- return obj;
- };
- })();
- /**
- * fixed CustomEvent
- */
- (function() {
- if (typeof window.CustomEvent === 'undefined') {
- function CustomEvent(event, params) {
- params = params || {
- bubbles: false,
- cancelable: false,
- detail: undefined
- };
- var evt = document.createEvent('Events');
- var bubbles = true;
- for (var name in params) {
- (name === 'bubbles') ? (bubbles = !!params[name]) : (evt[name] = params[name]);
- }
- evt.initEvent(event, bubbles, true);
- return evt;
- };
- CustomEvent.prototype = window.Event.prototype;
- window.CustomEvent = CustomEvent;
- }
- })();
- /*
- A shim for non ES5 supporting browsers.
- Adds function bind to Function prototype, so that you can do partial application.
- Works even with the nasty thing, where the first word is the opposite of extranet, the second one is the profession of Columbus, and the version number is 9, flipped 180 degrees.
- */
- Function.prototype.bind = Function.prototype.bind || function(to) {
- // Make an array of our arguments, starting from second argument
- var partial = Array.prototype.splice.call(arguments, 1),
- // We'll need the original function.
- fn = this;
- var bound = function() {
- // Join the already applied arguments to the now called ones (after converting to an array again).
- var args = partial.concat(Array.prototype.splice.call(arguments, 0));
- // If not being called as a constructor
- if (!(this instanceof bound)) {
- // return the result of the function called bound to target and partially applied.
- return fn.apply(to, args);
- }
- // If being called as a constructor, apply the function bound to self.
- fn.apply(this, args);
- }
- // Attach the prototype of the function to our newly created function.
- bound.prototype = fn.prototype;
- return bound;
- };
- /**
- * mui fixed classList
- * @param {type} document
- * @returns {undefined}
- */
- (function(document) {
- if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {
- Object.defineProperty(HTMLElement.prototype, 'classList', {
- get: function() {
- var self = this;
- function update(fn) {
- return function(value) {
- var classes = self.className.split(/\s+/),
- index = classes.indexOf(value);
- fn(classes, index, value);
- self.className = classes.join(" ");
- };
- }
- var ret = {
- add: update(function(classes, index, value) {
- ~index || classes.push(value);
- }),
- remove: update(function(classes, index) {
- ~index && classes.splice(index, 1);
- }),
- toggle: update(function(classes, index, value) {
- ~index ? classes.splice(index, 1) : classes.push(value);
- }),
- contains: function(value) {
- return !!~self.className.split(/\s+/).indexOf(value);
- },
- item: function(i) {
- return self.className.split(/\s+/)[i] || null;
- }
- };
- Object.defineProperty(ret, 'length', {
- get: function() {
- return self.className.split(/\s+/).length;
- }
- });
- return ret;
- }
- });
- }
- })(document);
- /**
- * mui fixed requestAnimationFrame
- * @param {type} window
- * @returns {undefined}
- */
- (function(window) {
- if (!window.requestAnimationFrame) {
- var lastTime = 0;
- window.requestAnimationFrame = window.webkitRequestAnimationFrame || function(callback, element) {
- var currTime = new Date().getTime();
- var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
- var id = window.setTimeout(function() {
- callback(currTime + timeToCall);
- }, timeToCall);
- lastTime = currTime + timeToCall;
- return id;
- };
- window.cancelAnimationFrame = window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || function(id) {
- clearTimeout(id);
- };
- };
- }(window));
- /**
- * fastclick(only for radio,checkbox)
- */
- (function($, window, name) {
- if (!$.os.android && !$.os.ios) { //目前仅识别android和ios
- return;
- }
- if (window.FastClick) {
- return;
- }
- var handle = function(event, target) {
- if (target.tagName === 'LABEL') {
- if (target.parentNode) {
- target = target.parentNode.querySelector('input');
- }
- }
- if (target && (target.type === 'radio' || target.type === 'checkbox')) {
- if (!target.disabled) { //disabled
- return target;
- }
- }
- return false;
- };
- $.registerTarget({
- name: name,
- index: 40,
- handle: handle,
- target: false
- });
- var dispatchEvent = function(event) {
- var targetElement = $.targets.click;
- if (targetElement) {
- var clickEvent, touch;
- // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect
- if (document.activeElement && document.activeElement !== targetElement) {
- document.activeElement.blur();
- }
- touch = event.detail.gesture.changedTouches[0];
- // Synthesise a click event, with an extra attribute so it can be tracked
- clickEvent = document.createEvent('MouseEvents');
- clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
- clickEvent.forwardedTouchEvent = true;
- targetElement.dispatchEvent(clickEvent);
- event.detail && event.detail.gesture.preventDefault();
- }
- };
- window.addEventListener('tap', dispatchEvent);
- window.addEventListener('doubletap', dispatchEvent);
- //捕获
- window.addEventListener('click', function(event) {
- if ($.targets.click) {
- if (!event.forwardedTouchEvent) { //stop click
- if (event.stopImmediatePropagation) {
- event.stopImmediatePropagation();
- } else {
- // Part of the hack for browsers that don't support Event#stopImmediatePropagation
- event.propagationStopped = true;
- }
- event.stopPropagation();
- event.preventDefault();
- return false;
- }
- }
- }, true);
- })(mui, window, 'click');
- (function($, document) {
- $(function() {
- if (!$.os.ios) {
- return;
- }
- var CLASS_FOCUSIN = 'mui-focusin';
- var CLASS_BAR_TAB = 'mui-bar-tab';
- var CLASS_BAR_FOOTER = 'mui-bar-footer';
- var CLASS_BAR_FOOTER_SECONDARY = 'mui-bar-footer-secondary';
- var CLASS_BAR_FOOTER_SECONDARY_TAB = 'mui-bar-footer-secondary-tab';
- // var content = document.querySelector('.' + CLASS_CONTENT);
- // if (content) {
- // document.body.insertBefore(content, document.body.firstElementChild);
- // }
- document.addEventListener('focusin', function(e) {
- if ($.os.plus) { //在父webview里边不fix
- if (window.plus) {
- if (plus.webview.currentWebview().children().length > 0) {
- return;
- }
- }
- }
- var target = e.target;
- //TODO 需考虑所有键盘弹起的情况
- if (target.tagName && (target.tagName === 'TEXTAREA' || (target.tagName === 'INPUT' && (target.type === 'text' || target.type === 'search' || target.type === 'number')))) {
- if (target.disabled || target.readOnly) {
- return;
- }
- document.body.classList.add(CLASS_FOCUSIN);
- var isFooter = false;
- for (; target && target !== document; target = target.parentNode) {
- var classList = target.classList;
- if (classList && classList.contains(CLASS_BAR_TAB) || classList.contains(CLASS_BAR_FOOTER) || classList.contains(CLASS_BAR_FOOTER_SECONDARY) || classList.contains(CLASS_BAR_FOOTER_SECONDARY_TAB)) {
- isFooter = true;
- break;
- }
- }
- if (isFooter) {
- var scrollTop = document.body.scrollHeight;
- var scrollLeft = document.body.scrollLeft;
- setTimeout(function() {
- window.scrollTo(scrollLeft, scrollTop);
- }, 20);
- }
- }
- });
- document.addEventListener('focusout', function(e) {
- var classList = document.body.classList;
- if (classList.contains(CLASS_FOCUSIN)) {
- classList.remove(CLASS_FOCUSIN);
- setTimeout(function() {
- window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
- }, 20);
- }
- });
- });
- })(mui, document);
- /**
- * mui namespace(optimization)
- * @param {type} $
- * @returns {undefined}
- */
- (function($) {
- $.namespace = 'mui';
- $.classNamePrefix = $.namespace + '-';
- $.classSelectorPrefix = '.' + $.classNamePrefix;
- /**
- * 返回正确的className
- * @param {type} className
- * @returns {String}
- */
- $.className = function(className) {
- return $.classNamePrefix + className;
- };
- /**
- * 返回正确的classSelector
- * @param {type} classSelector
- * @returns {String}
- */
- $.classSelector = function(classSelector) {
- return classSelector.replace(/\./g, $.classSelectorPrefix);
- };
- /**
- * 返回正确的eventName
- * @param {type} event
- * @param {type} module
- * @returns {String}
- */
- $.eventName = function(event, module) {
- return event + ($.namespace ? ('.' + $.namespace) : '') + ( module ? ('.' + module) : '');
- };
- })(mui);
- /**
- * mui gestures
- * @param {type} $
- * @param {type} window
- * @returns {undefined}
- */
- (function($, window) {
- $.gestures = {
- session: {}
- };
- /**
- * Gesture preventDefault
- * @param {type} e
- * @returns {undefined}
- */
- $.preventDefault = function(e) {
- e.preventDefault();
- };
- /**
- * Gesture stopPropagation
- * @param {type} e
- * @returns {undefined}
- */
- $.stopPropagation = function(e) {
- e.stopPropagation();
- };
- /**
- * register gesture
- * @param {type} gesture
- * @returns {$.gestures}
- */
- $.addGesture = function(gesture) {
- return $.addAction('gestures', gesture);
- };
- var round = Math.round;
- var abs = Math.abs;
- var sqrt = Math.sqrt;
- var atan = Math.atan;
- var atan2 = Math.atan2;
- /**
- * distance
- * @param {type} p1
- * @param {type} p2
- * @returns {Number}
- */
- var getDistance = function(p1, p2, props) {
- if(!props) {
- props = ['x', 'y'];
- }
- var x = p2[props[0]] - p1[props[0]];
- var y = p2[props[1]] - p1[props[1]];
- return sqrt((x * x) + (y * y));
- };
- /**
- * scale
- * @param {Object} starts
- * @param {Object} moves
- */
- var getScale = function(starts, moves) {
- if(starts.length >= 2 && moves.length >= 2) {
- var props = ['pageX', 'pageY'];
- return getDistance(moves[1], moves[0], props) / getDistance(starts[1], starts[0], props);
- }
- return 1;
- };
- /**
- * angle
- * @param {type} p1
- * @param {type} p2
- * @returns {Number}
- */
- var getAngle = function(p1, p2, props) {
- if(!props) {
- props = ['x', 'y'];
- }
- var x = p2[props[0]] - p1[props[0]];
- var y = p2[props[1]] - p1[props[1]];
- return atan2(y, x) * 180 / Math.PI;
- };
- /**
- * direction
- * @param {Object} x
- * @param {Object} y
- */
- var getDirection = function(x, y) {
- if(x === y) {
- return '';
- }
- if(abs(x) >= abs(y)) {
- return x > 0 ? 'left' : 'right';
- }
- return y > 0 ? 'up' : 'down';
- };
- /**
- * rotation
- * @param {Object} start
- * @param {Object} end
- */
- var getRotation = function(start, end) {
- var props = ['pageX', 'pageY'];
- return getAngle(end[1], end[0], props) - getAngle(start[1], start[0], props);
- };
- /**
- * px per ms
- * @param {Object} deltaTime
- * @param {Object} x
- * @param {Object} y
- */
- var getVelocity = function(deltaTime, x, y) {
- return {
- x: x / deltaTime || 0,
- y: y / deltaTime || 0
- };
- };
- /**
- * detect gestures
- * @param {type} event
- * @param {type} touch
- * @returns {undefined}
- */
- var detect = function(event, touch) {
- if($.gestures.stoped) {
- return;
- }
- $.doAction('gestures', function(index, gesture) {
- if(!$.gestures.stoped) {
- if($.options.gestureConfig[gesture.name] !== false) {
- gesture.handle(event, touch);
- }
- }
- });
- };
- /**
- * 暂时无用
- * @param {Object} node
- * @param {Object} parent
- */
- var hasParent = function(node, parent) {
- while(node) {
- if(node == parent) {
- return true;
- }
- node = node.parentNode;
- }
- return false;
- };
- var uniqueArray = function(src, key, sort) {
- var results = [];
- var values = [];
- var i = 0;
- while(i < src.length) {
- var val = key ? src[i][key] : src[i];
- if(values.indexOf(val) < 0) {
- results.push(src[i]);
- }
- values[i] = val;
- i++;
- }
- if(sort) {
- if(!key) {
- results = results.sort();
- } else {
- results = results.sort(function sortUniqueArray(a, b) {
- return a[key] > b[key];
- });
- }
- }
- return results;
- };
- var getMultiCenter = function(touches) {
- var touchesLength = touches.length;
- if(touchesLength === 1) {
- return {
- x: round(touches[0].pageX),
- y: round(touches[0].pageY)
- };
- }
- var x = 0;
- var y = 0;
- var i = 0;
- while(i < touchesLength) {
- x += touches[i].pageX;
- y += touches[i].pageY;
- i++;
- }
- return {
- x: round(x / touchesLength),
- y: round(y / touchesLength)
- };
- };
- var multiTouch = function() {
- return $.options.gestureConfig.pinch;
- };
- var copySimpleTouchData = function(touch) {
- var touches = [];
- var i = 0;
- while(i < touch.touches.length) {
- touches[i] = {
- pageX: round(touch.touches[i].pageX),
- pageY: round(touch.touches[i].pageY)
- };
- i++;
- }
- return {
- timestamp: $.now(),
- gesture: touch.gesture,
- touches: touches,
- center: getMultiCenter(touch.touches),
- deltaX: touch.deltaX,
- deltaY: touch.deltaY
- };
- };
- var calDelta = function(touch) {
- var session = $.gestures.session;
- var center = touch.center;
- var offset = session.offsetDelta || {};
- var prevDelta = session.prevDelta || {};
- var prevTouch = session.prevTouch || {};
- if(touch.gesture.type === $.EVENT_START || touch.gesture.type === $.EVENT_END) {
- prevDelta = session.prevDelta = {
- x: prevTouch.deltaX || 0,
- y: prevTouch.deltaY || 0
- };
- offset = session.offsetDelta = {
- x: center.x,
- y: center.y
- };
- }
- touch.deltaX = prevDelta.x + (center.x - offset.x);
- touch.deltaY = prevDelta.y + (center.y - offset.y);
- };
- var calTouchData = function(touch) {
- var session = $.gestures.session;
- var touches = touch.touches;
- var touchesLength = touches.length;
- if(!session.firstTouch) {
- session.firstTouch = copySimpleTouchData(touch);
- }
- if(multiTouch() && touchesLength > 1 && !session.firstMultiTouch) {
- session.firstMultiTouch = copySimpleTouchData(touch);
- } else if(touchesLength === 1) {
- session.firstMultiTouch = false;
- }
- var firstTouch = session.firstTouch;
- var firstMultiTouch = session.firstMultiTouch;
- var offsetCenter = firstMultiTouch ? firstMultiTouch.center : firstTouch.center;
- var center = touch.center = getMultiCenter(touches);
- touch.timestamp = $.now();
- touch.deltaTime = touch.timestamp - firstTouch.timestamp;
- touch.angle = getAngle(offsetCenter, center);
- touch.distance = getDistance(offsetCenter, center);
- calDelta(touch);
- touch.offsetDirection = getDirection(touch.deltaX, touch.deltaY);
- touch.scale = firstMultiTouch ? getScale(firstMultiTouch.touches, touches) : 1;
- touch.rotation = firstMultiTouch ? getRotation(firstMultiTouch.touches, touches) : 0;
- calIntervalTouchData(touch);
- };
- var CAL_INTERVAL = 25;
- var calIntervalTouchData = function(touch) {
- var session = $.gestures.session;
- var last = session.lastInterval || touch;
- var deltaTime = touch.timestamp - last.timestamp;
- var velocity;
- var velocityX;
- var velocityY;
- var direction;
- if(touch.gesture.type != $.EVENT_CANCEL && (deltaTime > CAL_INTERVAL || last.velocity === undefined)) {
- var deltaX = last.deltaX - touch.deltaX;
- var deltaY = last.deltaY - touch.deltaY;
- var v = getVelocity(deltaTime, deltaX, deltaY);
- velocityX = v.x;
- velocityY = v.y;
- velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
- direction = getDirection(deltaX, deltaY) || last.direction;
- session.lastInterval = touch;
- } else {
- velocity = last.velocity;
- velocityX = last.velocityX;
- velocityY = last.velocityY;
- direction = last.direction;
- }
- touch.velocity = velocity;
- touch.velocityX = velocityX;
- touch.velocityY = velocityY;
- touch.direction = direction;
- };
- var targetIds = {};
- var convertTouches = function(touches) {
- for(var i = 0; i < touches.length; i++) {
- !touches['identifier'] && (touches['identifier'] = 0);
- }
- return touches;
- };
- var getTouches = function(event, touch) {
- var allTouches = convertTouches($.slice.call(event.touches || [event]));
- var type = event.type;
- var targetTouches = [];
- var changedTargetTouches = [];
- //当touchstart或touchmove且touches长度为1,直接获得all和changed
- if((type === $.EVENT_START || type === $.EVENT_MOVE) && allTouches.length === 1) {
- targetIds[allTouches[0].identifier] = true;
- targetTouches = allTouches;
- changedTargetTouches = allTouches;
- touch.target = event.target;
- } else {
- var i = 0;
- var targetTouches = [];
- var changedTargetTouches = [];
- var changedTouches = convertTouches($.slice.call(event.changedTouches || [event]));
- touch.target = event.target;
- var sessionTarget = $.gestures.session.target || event.target;
- targetTouches = allTouches.filter(function(touch) {
- return hasParent(touch.target, sessionTarget);
- });
- if(type === $.EVENT_START) {
- i = 0;
- while(i < targetTouches.length) {
- targetIds[targetTouches[i].identifier] = true;
- i++;
- }
- }
- i = 0;
- while(i < changedTouches.length) {
- if(targetIds[changedTouches[i].identifier]) {
- changedTargetTouches.push(changedTouches[i]);
- }
- if(type === $.EVENT_END || type === $.EVENT_CANCEL) {
- delete targetIds[changedTouches[i].identifier];
- }
- i++;
- }
- if(!changedTargetTouches.length) {
- return false;
- }
- }
- targetTouches = uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true);
- var touchesLength = targetTouches.length;
- var changedTouchesLength = changedTargetTouches.length;
- if(type === $.EVENT_START && touchesLength - changedTouchesLength === 0) { //first
- touch.isFirst = true;
- $.gestures.touch = $.gestures.session = {
- target: event.target
- };
- }
- touch.isFinal = ((type === $.EVENT_END || type === $.EVENT_CANCEL) && (touchesLength - changedTouchesLength === 0));
- touch.touches = targetTouches;
- touch.changedTouches = changedTargetTouches;
- return true;
- };
- var handleTouchEvent = function(event) {
- var touch = {
- gesture: event
- };
- var touches = getTouches(event, touch);
- if(!touches) {
- return;
- }
- calTouchData(touch);
- detect(event, touch);
- $.gestures.session.prevTouch = touch;
- if(event.type === $.EVENT_END && !$.isTouchable) {
- $.gestures.touch = $.gestures.session = {};
- }
- };
- var supportsPassive = (function checkPassiveListener() {
- var supportsPassive = false;
- try {
- var opts = Object.defineProperty({}, 'passive', {
- get: function get() {
- supportsPassive = true;
- },
- });
- window.addEventListener('testPassiveListener', null, opts);
- } catch(e) {
- // No support
- }
- return supportsPassive;
- }())
- window.addEventListener($.EVENT_START, handleTouchEvent);
- window.addEventListener($.EVENT_MOVE, handleTouchEvent, supportsPassive ? {
- passive: false,
- capture: false
- } : false);
- window.addEventListener($.EVENT_END, handleTouchEvent);
- window.addEventListener($.EVENT_CANCEL, handleTouchEvent);
- //fixed hashchange(android)
- window.addEventListener($.EVENT_CLICK, function(e) {
- //TODO 应该判断当前target是不是在targets.popover内部,而不是非要相等
- if(($.os.android || $.os.ios) && (($.targets.popover && e.target === $.targets.popover) || ($.targets.tab) || $.targets.offcanvas || $.targets.modal)) {
- e.preventDefault();
- }
- }, true);
- //增加原生滚动识别
- $.isScrolling = false;
- var scrollingTimeout = null;
- window.addEventListener('scroll', function() {
- $.isScrolling = true;
- scrollingTimeout && clearTimeout(scrollingTimeout);
- scrollingTimeout = setTimeout(function() {
- $.isScrolling = false;
- }, 250);
- });
- })(mui, window);
- /**
- * mui gesture flick[left|right|up|down]
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var flickStartTime = 0;
- var handle = function(event, touch) {
- var session = $.gestures.session;
- var options = this.options;
- var now = $.now();
- switch (event.type) {
- case $.EVENT_MOVE:
- if (now - flickStartTime > 300) {
- flickStartTime = now;
- session.flickStart = touch.center;
- }
- break;
- case $.EVENT_END:
- case $.EVENT_CANCEL:
- touch.flick = false;
- if (session.flickStart && options.flickMaxTime > (now - flickStartTime) && touch.distance > options.flickMinDistince) {
- touch.flick = true;
- touch.flickTime = now - flickStartTime;
- touch.flickDistanceX = touch.center.x - session.flickStart.x;
- touch.flickDistanceY = touch.center.y - session.flickStart.y;
- $.trigger(session.target, name, touch);
- $.trigger(session.target, name + touch.direction, touch);
- }
- break;
- }
- };
- /**
- * mui gesture flick
- */
- $.addGesture({
- name: name,
- index: 5,
- handle: handle,
- options: {
- flickMaxTime: 200,
- flickMinDistince: 10
- }
- });
- })(mui, 'flick');
- /**
- * mui gesture swipe[left|right|up|down]
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var handle = function(event, touch) {
- var session = $.gestures.session;
- if (event.type === $.EVENT_END || event.type === $.EVENT_CANCEL) {
- var options = this.options;
- touch.swipe = false;
- //TODO 后续根据velocity计算
- if (touch.direction && options.swipeMaxTime > touch.deltaTime && touch.distance > options.swipeMinDistince) {
- touch.swipe = true;
- $.trigger(session.target, name, touch);
- $.trigger(session.target, name + touch.direction, touch);
- }
- }
- };
- /**
- * mui gesture swipe
- */
- $.addGesture({
- name: name,
- index: 10,
- handle: handle,
- options: {
- swipeMaxTime: 300,
- swipeMinDistince: 18
- }
- });
- })(mui, 'swipe');
- /**
- * mui gesture drag[start|left|right|up|down|end]
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var handle = function(event, touch) {
- var session = $.gestures.session;
- switch (event.type) {
- case $.EVENT_START:
- break;
- case $.EVENT_MOVE:
- if (!touch.direction || !session.target) {
- return;
- }
- //修正direction,可在session期间自行锁定拖拽方向,方便开发scroll类不同方向拖拽插件嵌套
- if (session.lockDirection && session.startDirection) {
- if (session.startDirection && session.startDirection !== touch.direction) {
- if (session.startDirection === 'up' || session.startDirection === 'down') {
- touch.direction = touch.deltaY < 0 ? 'up' : 'down';
- } else {
- touch.direction = touch.deltaX < 0 ? 'left' : 'right';
- }
- }
- }
- if (!session.drag) {
- session.drag = true;
- $.trigger(session.target, name + 'start', touch);
- }
- $.trigger(session.target, name, touch);
- $.trigger(session.target, name + touch.direction, touch);
- break;
- case $.EVENT_END:
- case $.EVENT_CANCEL:
- if (session.drag && touch.isFinal) {
- $.trigger(session.target, name + 'end', touch);
- }
- break;
- }
- };
- /**
- * mui gesture drag
- */
- $.addGesture({
- name: name,
- index: 20,
- handle: handle,
- options: {
- fingers: 1
- }
- });
- })(mui, 'drag');
- /**
- * mui gesture tap and doubleTap
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var lastTarget;
- var lastTapTime;
- var handle = function(event, touch) {
- var session = $.gestures.session;
- var options = this.options;
- switch (event.type) {
- case $.EVENT_END:
- if (!touch.isFinal) {
- return;
- }
- var target = session.target;
- if (!target || (target.disabled || (target.classList && target.classList.contains('mui-disabled')))) {
- return;
- }
- if (touch.distance < options.tapMaxDistance && touch.deltaTime < options.tapMaxTime) {
- if ($.options.gestureConfig.doubletap && lastTarget && (lastTarget === target)) { //same target
- if (lastTapTime && (touch.timestamp - lastTapTime) < options.tapMaxInterval) {
- $.trigger(target, 'doubletap', touch);
- lastTapTime = $.now();
- lastTarget = target;
- return;
- }
- }
- $.trigger(target, name, touch);
- lastTapTime = $.now();
- lastTarget = target;
- }
- break;
- }
- };
- /**
- * mui gesture tap
- */
- $.addGesture({
- name: name,
- index: 30,
- handle: handle,
- options: {
- fingers: 1,
- tapMaxInterval: 300,
- tapMaxDistance: 5,
- tapMaxTime: 250
- }
- });
- })(mui, 'tap');
- /**
- * mui gesture longtap
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var timer;
- var handle = function(event, touch) {
- var session = $.gestures.session;
- var options = this.options;
- switch (event.type) {
- case $.EVENT_START:
- clearTimeout(timer);
- timer = setTimeout(function() {
- $.trigger(session.target, name, touch);
- }, options.holdTimeout);
- break;
- case $.EVENT_MOVE:
- if (touch.distance > options.holdThreshold) {
- clearTimeout(timer);
- }
- break;
- case $.EVENT_END:
- case $.EVENT_CANCEL:
- clearTimeout(timer);
- break;
- }
- };
- /**
- * mui gesture longtap
- */
- $.addGesture({
- name: name,
- index: 10,
- handle: handle,
- options: {
- fingers: 1,
- holdTimeout: 500,
- holdThreshold: 2
- }
- });
- })(mui, 'longtap');
- /**
- * mui gesture hold
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var timer;
- var handle = function(event, touch) {
- var session = $.gestures.session;
- var options = this.options;
- switch (event.type) {
- case $.EVENT_START:
- if ($.options.gestureConfig.hold) {
- timer && clearTimeout(timer);
- timer = setTimeout(function() {
- touch.hold = true;
- $.trigger(session.target, name, touch);
- }, options.holdTimeout);
- }
- break;
- case $.EVENT_MOVE:
- break;
- case $.EVENT_END:
- case $.EVENT_CANCEL:
- if (timer) {
- clearTimeout(timer) && (timer = null);
- $.trigger(session.target, 'release', touch);
- }
- break;
- }
- };
- /**
- * mui gesture hold
- */
- $.addGesture({
- name: name,
- index: 10,
- handle: handle,
- options: {
- fingers: 1,
- holdTimeout: 0
- }
- });
- })(mui, 'hold');
- /**
- * mui gesture pinch
- * @param {type} $
- * @param {type} name
- * @returns {undefined}
- */
- (function($, name) {
- var handle = function(event, touch) {
- var options = this.options;
- var session = $.gestures.session;
- switch (event.type) {
- case $.EVENT_START:
- break;
- case $.EVENT_MOVE:
- if ($.options.gestureConfig.pinch) {
- if (touch.touches.length < 2) {
- return;
- }
- if (!session.pinch) { //start
- session.pinch = true;
- $.trigger(session.target, name + 'start', touch);
- }
- $.trigger(session.target, name, touch);
- var scale = touch.scale;
- var rotation = touch.rotation;
- var lastScale = typeof touch.lastScale === 'undefined' ? 1 : touch.lastScale;
- var scaleDiff = 0.000000000001; //防止scale与lastScale相等,不触发事件的情况。
- if (scale > lastScale) { //out
- lastScale = scale - scaleDiff;
- $.trigger(session.target, name + 'out', touch);
- } //in
- else if (scale < lastScale) {
- lastScale = scale + scaleDiff;
- $.trigger(session.target, name + 'in', touch);
- }
- if (Math.abs(rotation) > options.minRotationAngle) {
- $.trigger(session.target, 'rotate', touch);
- }
- }
- break;
- case $.EVENT_END:
- case $.EVENT_CANCEL:
- if ($.options.gestureConfig.pinch && session.pinch && touch.touches.length === 2) {
- session.pinch = false;
- $.trigger(session.target, name + 'end', touch);
- }
- break;
- }
- };
- /**
- * mui gesture pinch
- */
- $.addGesture({
- name: name,
- index: 10,
- handle: handle,
- options: {
- minRotationAngle: 0
- }
- });
- })(mui, 'pinch');
- /**
- * mui.init
- * @param {type} $
- * @returns {undefined}
- */
- (function($) {
- $.global = $.options = {
- gestureConfig: {
- tap: true,
- doubletap: false,
- longtap: false,
- hold: false,
- flick: true,
- swipe: true,
- drag: true,
- pinch: false
- }
- };
- /**
- *
- * @param {type} options
- * @returns {undefined}
- */
- $.initGlobal = function(options) {
- $.options = $.extend(true, $.global, options);
- return this;
- };
- var inits = {};
- /**
- * 单页配置 初始化
- * @param {object} options
- */
- $.init = function(options) {
- $.options = $.extend(true, $.global, options || {});
- $.ready(function() {
- $.doAction('inits', function(index, init) {
- var isInit = !!(!inits[init.name] || init.repeat);
- if (isInit) {
- init.handle.call($);
- inits[init.name] = true;
- }
- });
- });
- return this;
- };
- /**
- * 增加初始化执行流程
- * @param {function} init
- */
- $.addInit = function(init) {
- return $.addAction('inits', init);
- };
- /**
- * 处理html5版本subpages
- */
- $.addInit({
- name: 'iframe',
- index: 100,
- handle: function() {
- var options = $.options;
- var subpages = options.subpages || [];
- if (!$.os.plus && subpages.length) {
- //暂时只处理单个subpage。后续可以考虑支持多个subpage
- createIframe(subpages[0]);
- }
- }
- });
- var createIframe = function(options) {
- var wrapper = document.createElement('div');
- wrapper.className = 'mui-iframe-wrapper';
- var styles = options.styles || {};
- if (typeof styles.top !== 'string') {
- styles.top = '0px';
- }
- if (typeof styles.bottom !== 'string') {
- styles.bottom = '0px';
- }
- wrapper.style.top = styles.top;
- wrapper.style.bottom = styles.bottom;
- var iframe = document.createElement('iframe');
- iframe.src = options.url;
- iframe.id = options.id || options.url;
- iframe.name = iframe.id;
- wrapper.appendChild(iframe);
- document.body.appendChild(wrapper);
- //目前仅处理微信
- $.os.wechat && handleScroll(wrapper, iframe);
- };
- function handleScroll(wrapper, iframe) {
- var key = 'MUI_SCROLL_POSITION_' + document.location.href + '_' + iframe.src;
- var scrollTop = (parseFloat(localStorage.getItem(key)) || 0);
- if (scrollTop) {
- (function(y) {
- iframe.onload = function() {
- window.scrollTo(0, y);
- };
- })(scrollTop);
- }
- setInterval(function() {
- var _scrollTop = window.scrollY;
- if (scrollTop !== _scrollTop) {
- localStorage.setItem(key, _scrollTop + '');
- scrollTop = _scrollTop;
- }
- }, 100);
- };
- $(function() {
- var classList = document.body.classList;
- var os = [];
- if ($.os.ios) {
- os.push({
- os: 'ios',
- version: $.os.version
- });
- classList.add('mui-ios');
- } else if ($.os.android) {
- os.push({
- os: 'android',
- version: $.os.version
- });
- classList.add('mui-android');
- }
- if ($.os.wechat) {
- os.push({
- os: 'wechat',
- version: $.os.wechat.version
- });
- classList.add('mui-wechat');
- }
- if (os.length) {
- $.each(os, function(index, osObj) {
- var version = '';
- var classArray = [];
- if (osObj.version) {
- $.each(osObj.version.split('.'), function(i, v) {
- version = version + (version ? '-' : '') + v;
- classList.add($.className(osObj.os + '-' + version));
- });
- }
- });
- }
- });
- })(mui);
- /**
- * mui.init 5+
- * @param {type} $
- * @returns {undefined}
- */
- (function($) {
- var defaultOptions = {
- swipeBack: false,
- preloadPages: [], //5+ lazyLoad webview
- preloadLimit: 10, //预加载窗口的数量限制(一旦超出,先进先出)
- keyEventBind: {
- backbutton: true,
- menubutton: true
- },
- titleConfig: {
- height: "44px",
- backgroundColor: "#f7f7f7", //导航栏背景色
- bottomBorderColor: "#cccccc", //底部边线颜色
- title: { //标题配置
- text: "", //标题文字
- position: {
- top: 0,
- left: 0,
- width: "100%",
- height: "100%"
- },
- styles: {
- color: "#000000",
- align: "center",
- family: "'Helvetica Neue',Helvetica,sans-serif",
- size: "17px",
- style: "normal",
- weight: "normal",
- fontSrc: ""
- }
- },
- back: {
- image: {
- base64Data: '',
- imgSrc: '',
- sprite: {
- top: '0px',
- left: '0px',
- width: '100%',
- height: '100%'
- },
- position: {
- top: "10px",
- left: "10px",
- width: "24px",
- height: "24px"
- }
- }
- }
- }
- };
- //默认页面动画
- var defaultShow = {
- event:"titleUpdate",
- autoShow: true,
- duration: 300,
- aniShow: 'slide-in-right',
- extras:{}
- };
- //若执行了显示动画初始化操作,则要覆盖默认配置
- if($.options.show) {
- defaultShow = $.extend(true, defaultShow, $.options.show);
- }
- $.currentWebview = null;
- $.extend(true, $.global, defaultOptions);
- $.extend(true, $.options, defaultOptions);
- /**
- * 等待动画配置
- * @param {type} options
- * @returns {Object}
- */
- $.waitingOptions = function(options) {
- return $.extend(true, {}, {
- autoShow: true,
- title: '',
- modal: false
- }, options);
- };
- /**
- * 窗口显示配置
- * @param {type} options
- * @returns {Object}
- */
- $.showOptions = function(options) {
- return $.extend(true, {}, defaultShow, options);
- };
- /**
- * 窗口默认配置
- * @param {type} options
- * @returns {Object}
- */
- $.windowOptions = function(options) {
- return $.extend({
- scalable: false,
- bounce: "" //vertical
- }, options);
- };
- /**
- * plusReady
- * @param {type} callback
- * @returns {_L6.$}
- */
- $.plusReady = function(callback) {
- if(window.plus) {
- setTimeout(function() { //解决callback与plusready事件的执行时机问题(典型案例:showWaiting,closeWaiting)
- callback();
- }, 0);
- } else {
- document.addEventListener("plusready", function() {
- callback();
- }, false);
- }
- return this;
- };
- /**
- * 5+ event(5+没提供之前我自己实现)
- * @param {type} webview
- * @param {type} eventType
- * @param {type} data
- * @returns {undefined}
- */
- $.fire = function(webview, eventType, data) {
- if(webview) {
- if(typeof data === 'undefined') {
- data = '';
- } else if(typeof data === 'boolean' || typeof data === 'number') {
- webview.evalJS("typeof mui!=='undefined'&&mui.receive('" + eventType + "'," + data + ")");
- return;
- } else if($.isPlainObject(data) || $.isArray(data)) {
- data = JSON.stringify(data || {}).replace(/\'/g, "\\u0027").replace(/\\/g, "\\u005c");
- }
- webview.evalJS("typeof mui!=='undefined'&&mui.receive('" + eventType + "','" + data + "')");
- }
- };
- /**
- * 5+ event(5+没提供之前我自己实现)
- * @param {type} eventType
- * @param {type} data
- * @returns {undefined}
- */
- $.receive = function(eventType, data) {
- if(eventType) {
- try {
- if(data && typeof data === 'string') {
- data = JSON.parse(data);
- }
- } catch(e) {}
- $.trigger(document, eventType, data);
- }
- };
- var triggerPreload = function(webview) {
- if(!webview.preloaded) { //保证仅触发一次
- $.fire(webview, 'preload');
- var list = webview.children();
- for(var i = 0; i < list.length; i++) {
- $.fire(list[i], 'preload');
- }
- webview.preloaded = true;
- }
- };
- var trigger = function(webview, eventType, timeChecked) {
- if(timeChecked) {
- if(!webview[eventType + 'ed']) {
- $.fire(webview, eventType);
- var list = webview.children();
- for(var i = 0; i < list.length; i++) {
- $.fire(list[i], eventType);
- }
- webview[eventType + 'ed'] = true;
- }
- } else {
- $.fire(webview, eventType);
- var list = webview.children();
- for(var i = 0; i < list.length; i++) {
- $.fire(list[i], eventType);
- }
- }
- };
- /**
- * 打开新窗口
- * @param {string} url 要打开的页面地址
- * @param {string} id 指定页面ID
- * @param {object} options 可选:参数,等待,窗口,显示配置{params:{},waiting:{},styles:{},show:{}}
- */
- $.openWindow = function(url, id, options) {
- if(typeof url === 'object') {
- options = url;
- url = options.url;
- id = options.id || url;
- } else {
- if(typeof id === 'object') {
- options = id;
- id = options.id || url;
- } else {
- id = id || url;
- }
- }
- if(!$.os.plus) {
- //TODO 先临时这么处理:手机上顶层跳,PC上parent跳
- if($.os.ios || $.os.android) {
- window.top.location.href = url;
- } else {
- window.parent.location.href = url;
- }
- return;
- }
- if(!window.plus) {
- return;
- }
- options = options || {};
- var params = options.params || {};
- var webview = null,
- webviewCache = null,
- nShow, nWaiting;
- if($.webviews[id]) {
- webviewCache = $.webviews[id];
- //webview真实存在,才能获取
- if(plus.webview.getWebviewById(id)) {
- webview = webviewCache.webview;
- }
- } else if(options.createNew !== true) {
- webview = plus.webview.getWebviewById(id);
- }
- if(webview) { //已缓存
- //每次show都需要传递动画参数;
- //预加载的动画参数优先级:openWindow配置>preloadPages配置>mui默认配置;
- nShow = webviewCache ? webviewCache.show : defaultShow;
- nShow = options.show ? $.extend(nShow, options.show) : nShow;
- nShow.autoShow && webview.show(nShow.aniShow, nShow.duration, function() {
- triggerPreload(webview);
- trigger(webview, 'pagebeforeshow', false);
- });
- if(webviewCache) {
- webviewCache.afterShowMethodName && webview.evalJS(webviewCache.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');
- }
- return webview;
- } else { //新窗口
- if(!url) {
- throw new Error('webview[' + id + '] does not exist');
- }
- //显示waiting
- var waitingConfig = $.waitingOptions(options.waiting);
- if(waitingConfig.autoShow) {
- nWaiting = plus.nativeUI.showWaiting(waitingConfig.title, waitingConfig.options);
- }
- //创建页面
- options = $.extend(options, {
- id: id,
- url: url
- });
- webview = $.createWindow(options);
- //显示
- nShow = $.showOptions(options.show);
- if(nShow.autoShow) {
- var showWebview = function() {
- //关闭等待框
- if(nWaiting) {
- nWaiting.close();
- }
- //显示页面
- webview.show(nShow.aniShow, nShow.duration, function() {},nShow.extras);
- options.afterShowMethodName && webview.evalJS(options.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');
- };
- //titleUpdate触发时机早于loaded,更换为titleUpdate后,可以更早的显示webview
- webview.addEventListener(nShow.event, showWebview, false);
- //loaded事件发生后,触发预加载和pagebeforeshow事件
- webview.addEventListener("loaded", function() {
- triggerPreload(webview);
- trigger(webview, 'pagebeforeshow', false);
- }, false);
- }
- }
- return webview;
- };
- $.openWindowWithTitle = function(options, titleConfig) {
- options = options || {};
- var url = options.url;
- var id = options.id || url;
- if(!$.os.plus) {
- //TODO 先临时这么处理:手机上顶层跳,PC上parent跳
- if($.os.ios || $.os.android) {
- window.top.location.href = url;
- } else {
- window.parent.location.href = url;
- }
- return;
- }
- if(!window.plus) {
- return;
- }
- var params = options.params || {};
- var webview = null,
- webviewCache = null,
- nShow, nWaiting;
- if($.webviews[id]) {
- webviewCache = $.webviews[id];
- //webview真实存在,才能获取
- if(plus.webview.getWebviewById(id)) {
- webview = webviewCache.webview;
- }
- } else if(options.createNew !== true) {
- webview = plus.webview.getWebviewById(id);
- }
- if(webview) { //已缓存
- //每次show都需要传递动画参数;
- //预加载的动画参数优先级:openWindow配置>preloadPages配置>mui默认配置;
- nShow = webviewCache ? webviewCache.show : defaultShow;
- nShow = options.show ? $.extend(nShow, options.show) : nShow;
- nShow.autoShow && webview.show(nShow.aniShow, nShow.duration, function() {
- triggerPreload(webview);
- trigger(webview, 'pagebeforeshow', false);
- });
- if(webviewCache) {
- webviewCache.afterShowMethodName && webview.evalJS(webviewCache.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');
- }
- return webview;
- } else { //新窗口
- if(!url) {
- throw new Error('webview[' + id + '] does not exist');
- }
- //显示waiting
- var waitingConfig = $.waitingOptions(options.waiting);
- if(waitingConfig.autoShow) {
- nWaiting = plus.nativeUI.showWaiting(waitingConfig.title, waitingConfig.options);
- }
- //创建页面
- options = $.extend(options, {
- id: id,
- url: url
- });
- webview = $.createWindow(options);
- if(titleConfig) { //处理原生头
- $.extend(true, $.options.titleConfig, titleConfig);
- var tid = $.options.titleConfig.id ? $.options.titleConfig.id : id + "_title";
- var view = new plus.nativeObj.View(tid, {
- top: 0,
- height: $.options.titleConfig.height,
- width: "100%",
- dock: "top",
- position: "dock"
- });
- view.drawRect($.options.titleConfig.backgroundColor); //绘制背景色
- var _b = parseInt($.options.titleConfig.height) - 1;
- view.drawRect($.options.titleConfig.bottomBorderColor, {
- top: _b + "px",
- left: "0px"
- }); //绘制底部边线
- //绘制文字
- if($.options.titleConfig.title.text){
- var _title = $.options.titleConfig.title;
- view.drawText(_title.text,_title.position , _title.styles);
- }
-
- //返回图标绘制
- var _back = $.options.titleConfig.back;
- var backClick = null;
- //优先字体
- //其次是图片
- var _backImage = _back.image;
- if(_backImage.base64Data || _backImage.imgSrc) {
- //TODO ��处需要处理百分比的情况
- backClick = {
- left:parseInt(_backImage.position.left),
- right:parseInt(_backImage.position.left) + parseInt(_backImage.position.width)
- };
- var bitmap = new plus.nativeObj.Bitmap(id + "_back");
- if(_backImage.base64Data) { //优先base64编码字符串
- bitmap.loadBase64Data(_backImage.base64Data);
- } else { //其次加载图片文件
- bitmap.load(_backImage.imgSrc);
- }
- view.drawBitmap(bitmap,_backImage.sprite , _backImage.position);
- }
- //处理点击事件
- view.setTouchEventRect({
- top: "0px",
- left: "0px",
- width: "100%",
- height: "100%"
- });
- view.interceptTouchEvent(true);
- view.addEventListener("click", function(e) {
- var x = e.clientX;
-
- //返回按钮点击
- if(backClick&& x > backClick.left && x < backClick.right){
- if( _back.click && $.isFunction(_back.click)){
- _back.click();
- }else{
- webview.evalJS("window.mui&&mui.back();");
- }
- }
- }, false);
- webview.append(view);
- }
- //显示
- nShow = $.showOptions(options.show);
- if(nShow.autoShow) {
- //titleUpdate触发时机早于loaded,更换为titleUpdate后,可以更早的显示webview
- webview.addEventListener(nShow.event, function () {
- //关闭等待框
- if(nWaiting) {
- nWaiting.close();
- }
- //显示页面
- webview.show(nShow.aniShow, nShow.duration, function() {},nShow.extras);
- }, false);
- }
- }
- return webview;
- };
- /**
- * 根据配置信息创建一个webview
- * @param {type} options
- * @param {type} isCreate
- * @returns {webview}
- */
- $.createWindow = function(options, isCreate) {
- if(!window.plus) {
- return;
- }
- var id = options.id || options.url;
- var webview;
- if(options.preload) {
- if($.webviews[id] && $.webviews[id].webview.getURL()) { //已经cache
- webview = $.webviews[id].webview;
- } else { //新增预加载窗口
- //判断是否携带createNew参数,默认为false
- if(options.createNew !== true) {
- webview = plus.webview.getWebviewById(id);
- }
- //之前没有,那就新创建
- if(!webview) {
- webview = plus.webview.create(options.url, id, $.windowOptions(options.styles), $.extend({
- preload: true
- }, options.extras));
- if(options.subpages) {
- $.each(options.subpages, function(index, subpage) {
- var subpageId = subpage.id || subpage.url;
- if(subpageId) { //过滤空对象
- var subWebview = plus.webview.getWebviewById(subpageId);
- if(!subWebview) { //如果该webview不存在,则创建
- subWebview = plus.webview.create(subpage.url, subpageId, $.windowOptions(subpage.styles), $.extend({
- preload: true
- }, subpage.extras));
- }
- webview.append(subWebview);
- }
- });
- }
- }
- }
- //TODO 理论上,子webview也应该计算到预加载队列中,但这样就麻烦了,要退必须退整体,否则可能出现问题;
- $.webviews[id] = {
- webview: webview, //目前仅preload的缓存webview
- preload: true,
- show: $.showOptions(options.show),
- afterShowMethodName: options.afterShowMethodName //就不应该用evalJS。应该是通过事件消息通讯
- };
- //索引该预加载窗口
- var preloads = $.data.preloads;
- var index = preloads.indexOf(id);
- if(~index) { //删除已存在的(变相调整插入位置)
- preloads.splice(index, 1);
- }
- preloads.push(id);
- if(preloads.length > $.options.preloadLimit) {
- //先进先出
- var first = $.data.preloads.shift();
- var webviewCache = $.webviews[first];
- if(webviewCache && webviewCache.webview) {
- //需要将自己打开的所有页面,全部close;
- //关闭该预加载webview
- $.closeAll(webviewCache.webview);
- }
- //删除缓存
- delete $.webviews[first];
- }
- } else {
- if(isCreate !== false) { //直接创建非预加载窗口
- webview = plus.webview.create(options.url, id, $.windowOptions(options.styles), options.extras);
- if(options.subpages) {
- $.each(options.subpages, function(index, subpage) {
- var subpageId = subpage.id || subpage.url;
- var subWebview = plus.webview.getWebviewById(subpageId);
- if(!subWebview) {
- subWebview = plus.webview.create(subpage.url, subpageId, $.windowOptions(subpage.styles), subpage.extras);
- }
- webview.append(subWebview);
- });
- }
- }
- }
- return webview;
- };
- /**
- * 预加载
- */
- $.preload = function(options) {
- //调用预加载函数,不管是否传递preload参数,强制变为true
- if(!options.preload) {
- options.preload = true;
- }
- return $.createWindow(options);
- };
- /**
- *关闭当前webview打开的所有webview;
- */
- $.closeOpened = function(webview) {
- var opened = webview.opened();
- if(opened) {
- for(var i = 0, len = opened.length; i < len; i++) {
- var openedWebview = opened[i];
- var open_open = openedWebview.opened();
- if(open_open && open_open.length > 0) {
- //关闭打开的webview
- $.closeOpened(openedWebview);
- //关闭自己
- openedWebview.close("none");
- } else {
- //如果直接孩子节点,就不用关闭了,因为父关闭的时候,会自动关闭子;
- if(openedWebview.parent() !== webview) {
- openedWebview.close('none');
- }
- }
- }
- }
- };
- $.closeAll = function(webview, aniShow) {
- $.closeOpened(webview);
- if(aniShow) {
- webview.close(aniShow);
- } else {
- webview.close();
- }
- };
- /**
- * 批量创建webview
- * @param {type} options
- * @returns {undefined}
- */
- $.createWindows = function(options) {
- $.each(options, function(index, option) {
- //初始化预加载窗口(创建)和非预加载窗口(仅配置,不创建)
- $.createWindow(option, false);
- });
- };
- /**
- * 创建当前页面的子webview
- * @param {type} options
- * @returns {webview}
- */
- $.appendWebview = function(options) {
- if(!window.plus) {
- return;
- }
- var id = options.id || options.url;
- var webview;
- if(!$.webviews[id]) { //保证执行一遍
- //TODO 这里也有隐患,比如某个webview不是作为subpage创建的,而是作为target webview的话;
- if(!plus.webview.getWebviewById(id)) {
- webview = plus.webview.create(options.url, id, options.styles, options.extras);
- }
- //之前的实现方案:子窗口loaded之后再append到父窗口中;
- //问题:部分子窗口loaded事件发生较晚,此时执行父窗口的children方法会返回空,导致父子通讯失败;
- // 比如父页面执行完preload事件后,需触发子页面的preload事件,此时未append的话,就无法触发;
- //修改方式:不再监控loaded事件,直接append
- //by chb@20150521
- // webview.addEventListener('loaded', function() {
- plus.webview.currentWebview().append(webview);
- // });
- $.webviews[id] = options;
- }
- return webview;
- };
- //全局webviews
- $.webviews = {};
- //预加载窗口索引
- $.data.preloads = [];
- //$.currentWebview
- $.plusReady(function() {
- $.currentWebview = plus.webview.currentWebview();
- });
- $.addInit({
- name: '5+',
- index: 100,
- handle: function() {
- var options = $.options;
- var subpages = options.subpages || [];
- if($.os.plus) {
- $.plusReady(function() {
- //TODO 这里需要判断一下,最好等子窗口加载完毕后,再调用主窗口的show方法;
- //或者:在openwindow方法中,监听实现;
- $.each(subpages, function(index, subpage) {
- $.appendWebview(subpage);
- });
- //判断是否首页
- if(plus.webview.currentWebview() === plus.webview.getWebviewById(plus.runtime.appid)) {
- //首页需要自己激活预加载;
- //timeout因为子页面loaded之后才append的,防止子页面尚未append、从而导致其preload未触发的问题;
- setTimeout(function() {
- triggerPreload(plus.webview.currentWebview());
- }, 300);
- }
- //设置ios顶部状态栏颜色;
- if($.os.ios && $.options.statusBarBackground) {
- plus.navigator.setStatusBarBackground($.options.statusBarBackground);
- }
- if($.os.android && parseFloat($.os.version) < 4.4) {
- //解决Android平台4.4版本以下,resume后,父窗体标题延迟渲染的问题;
- if(plus.webview.currentWebview().parent() == null) {
- document.addEventListener("resume", function() {
- var body = document.body;
- body.style.display = 'none';
- setTimeout(function() {
- body.style.display = '';
- }, 10);
- });
- }
- }
- });
- } else {
- //已支持iframe嵌入
- // if (subpages.length > 0) {
- // var err = document.createElement('div');
- // err.className = 'mui-error';
- // //文字描述
- // var span = document.createElement('span');
- // span.innerHTML = '在该浏览器下,不支持创建子页面,具体参考';
- // err.appendChild(span);
- // var a = document.createElement('a');
- // a.innerHTML = '"mui框架适用场景"';
- // a.href = 'http://ask.dcloud.net.cn/article/113';
- // err.appendChild(a);
- // document.body.appendChild(err);
- // console.log('在该浏览器下,不支持创建子页面');
- // }
- }
- }
- });
- window.addEventListener('preload', function() {
- //处理预加载部分
- var webviews = $.options.preloadPages || [];
- $.plusReady(function() {
- $.each(webviews, function(index, webview) {
- $.createWindow($.extend(webview, {
- preload: true
- }));
- });
- });
- });
- $.supportStatusbarOffset = function() {
- return $.os.plus && $.os.ios && parseFloat($.os.version) >= 7;
- };
- $.ready(function() {
- //标识当前环境支持statusbar
- if($.supportStatusbarOffset()) {
- document.body.classList.add('mui-statusbar');
- }
- });
- })(mui);
- /**
- * mui back
- * @param {type} $
- * @param {type} window
- * @returns {undefined}
- */
- (function($, window) {
- /**
- * register back
- * @param {type} back
- * @returns {$.gestures}
- */
- $.addBack = function(back) {
- return $.addAction('backs', back);
- };
- /**
- * default
- */
- $.addBack({
- name: 'browser',
- index: 100,
- handle: function() {
- if (window.history.length > 1) {
- window.history.back();
- return true;
- }
- return false;
- }
- });
- /**
- * 后退
- */
- $.back = function() {
- if (typeof $.options.beforeback === 'function') {
- if ($.options.beforeback() === false) {
- return;
- }
- }
- $.doAction('backs');
- };
- window.addEventListener('tap', function(e) {
- var action = $.targets.action;
- if (action && action.classList.contains('mui-action-back')) {
- $.back();
- $.targets.action = false;
- }
- });
- window.addEventListener('swiperight', function(e) {
- var detail = e.detail;
- if ($.options.swipeBack === true && Math.abs(detail.angle) < 3) {
- $.back();
- }
- });
- })(mui, window);
- /**
- * mui back 5+
- * @param {type} $
- * @param {type} window
- * @returns {undefined}
- */
- (function($, window) {
- if ($.os.plus && $.os.android) {
- $.addBack({
- name: 'mui',
- index: 5,
- handle: function() {
-
- }
- });
- }
- //首次按下back按键的时间
- $.__back__first = null;
- /**
- * 5+ back
- */
- $.addBack({
- name: '5+',
- index: 10,
- handle: function() {
- if (!window.plus) {
- return false;
- }
- var wobj = plus.webview.currentWebview();
- var parent = wobj.parent();
- if (parent) {
- parent.evalJS('mui&&mui.back();');
- } else {
- wobj.canBack(function(e) {
- //by chb 暂时注释,在碰到类似popover之类的锚点的时候,需多次点击才能返回;
- if (e.canBack) { //webview history back
- window.history.back();
- } else { //webview close or hide
- //fixed by fxy 此处不应该用opener判断,因为用户有可能自己close掉当前窗口的opener。这样的话。opener就为空了,导致不能执行close
- if (wobj.id === plus.runtime.appid) { //首页
- //首页不存在opener的情况下,后退实际上应该是退出应用;
- //首次按键,提示‘再按一次退出应用’
- if (!$.__back__first) {
- $.__back__first = new Date().getTime();
- mui.toast('再按一次退出应用');
- setTimeout(function() {
- $.__back__first = null;
- }, 2000);
- } else {
- if (new Date().getTime() - $.__back__first < 2000) {
- plus.runtime.quit();
- }
- }
- } else { //其他页面,
- if (wobj.preload) {
- wobj.hide("auto");
- } else {
- //关闭页面时,需要将其打开的所有子页面全部关闭;
- $.closeAll(wobj);
- }
- }
- }
- });
- }
- return true;
- }
- });
- $.menu = function() {
- var menu = document.querySelector('.mui-action-menu');
- if (menu) {
- $.trigger(menu, $.EVENT_START); //临时处理menu无touchstart的话,找不到当前targets的问题
- $.trigger(menu, 'tap');
- } else { //执行父窗口的menu
- if (window.plus) {
- var wobj = $.currentWebview;
- var parent = wobj.parent();
- if (parent) { //又得evalJS
- parent.evalJS('mui&&mui.menu();');
- }
- }
- }
- };
- var __back = function() {
- $.back();
- };
- var __menu = function() {
- $.menu();
- };
- //默认监听
- $.plusReady(function() {
- if ($.options.keyEventBind.backbutton) {
- plus.key.addEventListener('backbutton', __back, false);
- }
- if ($.options.keyEventBind.menubutton) {
- plus.key.addEventListener('menubutton', __menu, false);
- }
- });
- //处理按键监听事件
- $.addInit({
- name: 'keyEventBind',
- index: 1000,
- handle: function() {
- $.plusReady(function() {
- //如果不为true,则移除默认监听
- if (!$.options.keyEventBind.backbutton) {
- plus.key.removeEventListener('backbutton', __back);
- }
- if (!$.options.keyEventBind.menubutton) {
- plus.key.removeEventListener('menubutton', __menu);
- }
- });
- }
- });
- })(mui, window);
- /**
- * mui.init pulldownRefresh
- * @param {type} $
- * @returns {undefined}
- */
- (function($) {
- $.addInit({
- name: 'pullrefresh',
- index: 1000,
- handle: function() {
- var options = $.options;
- var pullRefreshOptions = options.pullRefresh || {};
- var hasPulldown = pullRefreshOptions.down && pullRefreshOptions.down.hasOwnProperty('callback');
- var hasPullup = pullRefreshOptions.up && pullRefreshOptions.up.hasOwnProperty('callback');
- if(hasPulldown || hasPullup) {
- var container = pullRefreshOptions.container;
- if(container) {
- var $container = $(container);
- if($container.length === 1) {
- if($.os.plus) { //5+环境
- if(hasPulldown && pullRefreshOptions.down.style == "circle") { //原生转圈
- $.plusReady(function() {
- //这里改写$.fn.pullRefresh
- $.fn.pullRefresh = $.fn.pullRefresh_native;
- $container.pullRefresh(pullRefreshOptions);
- });
- } else if($.os.android) { //非原生转圈,但是Android环境
- $.plusReady(function() {
- //这里改写$.fn.pullRefresh
- $.fn.pullRefresh = $.fn.pullRefresh_native
- var webview = plus.webview.currentWebview();
- if(window.__NWin_Enable__ === false) { //不支持多webview
- $container.pullRefresh(pullRefreshOptions);
- } else {
- if(hasPullup) {
- //当前页面初始化pullup
- var upOptions = {};
- upOptions.up = pullRefreshOptions.up;
- upOptions.webviewId = webview.id || webview.getURL();
- $container.pullRefresh(upOptions);
- }
- if(hasPulldown) {
- var parent = webview.parent();
- var id = webview.id || webview.getURL();
- if(parent) {
- if(!hasPullup) { //如果没有上拉加载,需要手动初始化一个默认的pullRefresh,以便当前页面容器可以调用endPulldownToRefresh等方法
- $container.pullRefresh({
- webviewId: id
- });
- }
- var downOptions = {
- webviewId: id//子页面id
- };
- downOptions.down = $.extend({}, pullRefreshOptions.down);
- downOptions.down.callback = '_CALLBACK';
- //改写父页面的$.fn.pullRefresh
- parent.evalJS("mui.fn.pullRefresh=mui.fn.pullRefresh_native");
- //父页面初始化pulldown
- parent.evalJS("mui&&mui(document.querySelector('.mui-content')).pullRefresh('" + JSON.stringify(downOptions) + "')");
- }
- }
- }
- });
- } else { //非原生转圈,iOS环境
- $container.pullRefresh(pullRefreshOptions);
- }
- } else {
- $container.pullRefresh(pullRefreshOptions);
- }
- }
- }
- }
- }
- });
- })(mui);
- /**
- * mui ajax
- * @param {type} $
- * @returns {undefined}
- */
- (function($, window, undefined) {
- var jsonType = 'application/json';
- var htmlType = 'text/html';
- var rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
- var scriptTypeRE = /^(?:text|application)\/javascript/i;
- var xmlTypeRE = /^(?:text|application)\/xml/i;
- var blankRE = /^\s*$/;
- $.ajaxSettings = {
- type: 'GET',
- beforeSend: $.noop,
- success: $.noop,
- error: $.noop,
- complete: $.noop,
- context: null,
- xhr: function(protocol) {
- return new window.XMLHttpRequest();
- },
- accepts: {
- script: 'text/javascript, application/javascript, application/x-javascript',
- json: jsonType,
- xml: 'application/xml, text/xml',
- html: htmlType,
- text: 'text/plain'
- },
- timeout: 0,
- processData: true,
- cache: true
- };
- var ajaxBeforeSend = function(xhr, settings) {
- var context = settings.context
- if(settings.beforeSend.call(context, xhr, settings) === false) {
- return false;
- }
- };
- var ajaxSuccess = function(data, xhr, settings) {
- settings.success.call(settings.context, data, 'success', xhr);
- ajaxComplete('success', xhr, settings);
- };
- // type: "timeout", "error", "abort", "parsererror"
- var ajaxError = function(error, type, xhr, settings) {
- settings.error.call(settings.context, xhr, type, error);
- ajaxComplete(type, xhr, settings);
- };
- // status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
- var ajaxComplete = function(status, xhr, settings) {
- settings.complete.call(settings.context, xhr, status);
- };
- var serialize = function(params, obj, traditional, scope) {
- var type, array = $.isArray(obj),
- hash = $.isPlainObject(obj);
- $.each(obj, function(key, value) {
- type = $.type(value);
- if(scope) {
- key = traditional ? scope :
- scope + '[' + (hash || type === 'object' || type === 'array' ? key : '') + ']';
- }
- // handle data in serializeArray() format
- if(!scope && array) {
- params.add(value.name, value.value);
- }
- // recurse into nested objects
- else if(type === "array" || (!traditional && type === "object")) {
- serialize(params, value, traditional, key);
- } else {
- params.add(key, value);
- }
- });
- };
- var serializeData = function(options) {
- if(options.processData && options.data && typeof options.data !== "string") {
- var contentType = options.contentType;
- if(!contentType && options.headers) {
- contentType = options.headers['Content-Type'];
- }
- if(contentType && ~contentType.indexOf(jsonType)) { //application/json
- options.data = JSON.stringify(options.data);
- } else {
- options.data = $.param(options.data, options.traditional);
- }
- }
- if(options.data && (!options.type || options.type.toUpperCase() === 'GET')) {
- options.url = appendQuery(options.url, options.data);
- options.data = undefined;
- }
- };
- var appendQuery = function(url, query) {
- if(query === '') {
- return url;
- }
- return(url + '&' + query).replace(/[&?]{1,2}/, '?');
- };
- var mimeToDataType = function(mime) {
- if(mime) {
- mime = mime.split(';', 2)[0];
- }
- return mime && (mime === htmlType ? 'html' :
- mime === jsonType ? 'json' :
- scriptTypeRE.test(mime) ? 'script' :
- xmlTypeRE.test(mime) && 'xml') || 'text';
- };
- var parseArguments = function(url, data, success, dataType) {
- if($.isFunction(data)) {
- dataType = success, success = data, data = undefined;
- }
- if(!$.isFunction(success)) {
- dataType = success, success = undefined;
- }
- return {
- url: url,
- data: data,
- success: success,
- dataType: dataType
- };
- };
- $.ajax = function(url, options) {
- if(typeof url === "object") {
- options = url;
- url = undefined;
- }
- var settings = options || {};
- settings.url = url || settings.url;
- for(var key in $.ajaxSettings) {
- if(settings[key] === undefined) {
- settings[key] = $.ajaxSettings[key];
- }
- }
- serializeData(settings);
- var dataType = settings.dataType;
- if(settings.cache === false || ((!options || options.cache !== true) && ('script' === dataType))) {
- settings.url = appendQuery(settings.url, '_=' + $.now());
- }
- var mime = settings.accepts[dataType && dataType.toLowerCase()];
- var headers = {};
- var setHeader = function(name, value) {
- headers[name.toLowerCase()] = [name, value];
- };
- var protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol;
- var xhr = settings.xhr(settings);
- var nativeSetHeader = xhr.setRequestHeader;
- var abortTimeout;
- setHeader('X-Requested-With', 'XMLHttpRequest');
- setHeader('Accept', mime || '*/*');
- if(!!(mime = settings.mimeType || mime)) {
- if(mime.indexOf(',') > -1) {
- mime = mime.split(',', 2)[0];
- }
- xhr.overrideMimeType && xhr.overrideMimeType(mime);
- }
- if(settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() !== 'GET')) {
- setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded');
- }
- if(settings.headers) {
- for(var name in settings.headers)
- setHeader(name, settings.headers[name]);
- }
- xhr.setRequestHeader = setHeader;
- xhr.onreadystatechange = function() {
- if(xhr.readyState === 4) {
- xhr.onreadystatechange = $.noop;
- clearTimeout(abortTimeout);
- var result, error = false;
- var isLocal = protocol === 'file:';
- if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || (xhr.status === 0 && isLocal && xhr.responseText)) {
- dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'));
- result = xhr.responseText;
- try {
- // http://perfectionkills.com/global-eval-what-are-the-options/
- if(dataType === 'script') {
- (1, eval)(result);
- } else if(dataType === 'xml') {
- result = xhr.responseXML;
- } else if(dataType === 'json') {
- result = blankRE.test(result) ? null : $.parseJSON(result);
- }
- } catch(e) {
- error = e;
- }
- if(error) {
- ajaxError(error, 'parsererror', xhr, settings);
- } else {
- ajaxSuccess(result, xhr, settings);
- }
- } else {
- var status = xhr.status ? 'error' : 'abort';
- var statusText = xhr.statusText || null;
- if(isLocal) {
- status = 'error';
- statusText = '404';
- }
- ajaxError(statusText, status, xhr, settings);
- }
- }
- };
- if(ajaxBeforeSend(xhr, settings) === false) {
- xhr.abort();
- ajaxError(null, 'abort', xhr, settings);
- return xhr;
- }
- if(settings.xhrFields) {
- for(var name in settings.xhrFields) {
- xhr[name] = settings.xhrFields[name];
- }
- }
- var async = 'async' in settings ? settings.async : true;
- xhr.open(settings.type.toUpperCase(), settings.url, async, settings.username, settings.password);
- for(var name in headers) {
- xhr.setRequestHeader = nativeSetHeader;
- if(name=='content-type'&&headers[name][1]=='multipart/form-data'){
- //formdata 上传的不处理
- continue;
- }
- nativeSetHeader.apply(xhr, headers[name]);
- }
- if(settings.timeout > 0) {
- abortTimeout = setTimeout(function() {
- xhr.onreadystatechange = $.noop;
- xhr.abort();
- ajaxError(null, 'timeout', xhr, settings);
- }, settings.timeout);
- }
- xhr.send(settings.data ? settings.data : null);
- return xhr;
- };
- $.param = function(obj, traditional) {
- var params = [];
- params.add = function(k, v) {
- this.push(encodeURIComponent(k) + '=' + encodeURIComponent(v));
- };
- serialize(params, obj, traditional);
- return params.join('&').replace(/%20/g, '+');
- };
- $.get = function( /* url, data, success, dataType */ ) {
- return $.ajax(parseArguments.apply(null, arguments));
- };
- $.post = function( /* url, data, success, dataType */ ) {
- var options = parseArguments.apply(null, arguments);
- options.type = 'POST';
- return $.ajax(options);
- };
- $.getJSON = function( /* url, data, success */ ) {
- var options = parseArguments.apply(null, arguments);
- options.dataType = 'json';
- return $.ajax(options);
- };
- $.fn.load = function(url, data, success) {
- if(!this.length)
- return this;
- var self = this,
- parts = url.split(/\s/),
- selector,
- options = parseArguments(url, data, success),
- callback = options.success;
- if(parts.length > 1)
- options.url = parts[0], selector = parts[1];
- options.success = function(response) {
- if(selector) {
- var div = document.createElement('div');
- div.innerHTML = response.replace(rscript, "");
- var selectorDiv = document.createElement('div');
- var childs = div.querySelectorAll(selector);
- if(childs && childs.length > 0) {
- for(var i = 0, len = childs.length; i < len; i++) {
- selectorDiv.appendChild(childs[i]);
- }
- }
- self[0].innerHTML = selectorDiv.innerHTML;
- } else {
- self[0].innerHTML = response;
- }
- callback && callback.apply(self, arguments);
- };
- $.ajax(options);
- return this;
- };
- })(mui, window);
- /**
- * 5+ ajax
- */
- (function($) {
- var originAnchor = document.createElement('a');
- originAnchor.href = window.location.href;
- $.plusReady(function() {
- $.ajaxSettings = $.extend($.ajaxSettings, {
- xhr: function(settings) {
- if(settings.processData===false){
- return new window.XMLHttpRequest();
- }
- if (settings.crossDomain) { //强制使用plus跨域
- return new plus.net.XMLHttpRequest();
- }
- //仅在webview的url为远程文件,且ajax请求的资源不同源下使用plus.net.XMLHttpRequest
- if (originAnchor.protocol !== 'file:') {
- var urlAnchor = document.createElement('a');
- urlAnchor.href = settings.url;
- urlAnchor.href = urlAnchor.href;
- settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host);
- if (settings.crossDomain) {
- return new plus.net.XMLHttpRequest();
- }
- }
- if ($.os.ios && window.webkit && window.webkit.messageHandlers) { //wkwebview下同样使用5+ xhr
- return new plus.net.XMLHttpRequest();
- }
- return new window.XMLHttpRequest();
- }
- });
- });
- })(mui);
- /**
- * mui layout(offset[,position,width,height...])
- * @param {type} $
- * @param {type} window
- * @param {type} undefined
- * @returns {undefined}
- */
- (function($, window, undefined) {
- $.offset = function(element) {
- var box = {
- top : 0,
- left : 0
- };
- if ( typeof element.getBoundingClientRect !== undefined) {
- box = element.getBoundingClientRect();
- }
- return {
- top : box.top + window.pageYOffset - element.clientTop,
- left : box.left + window.pageXOffset - element.clientLeft
- };
- };
- })(mui, window);
- /**
- * mui animation
- */
- (function($, window) {
- /**
- * scrollTo
- */
- $.scrollTo = function(scrollTop, duration, callback) {
- duration = duration || 1000;
- var scroll = function(duration) {
- if (duration <= 0) {
- window.scrollTo(0, scrollTop);
- callback && callback();
- return;
- }
- var distaince = scrollTop - window.scrollY;
- setTimeout(function() {
- window.scrollTo(0, window.scrollY + distaince / duration * 10);
- scroll(duration - 10);
- }, 16.7);
- };
- scroll(duration);
- };
- $.animationFrame = function(cb) {
- var args, isQueued, context;
- return function() {
- args = arguments;
- context = this;
- if (!isQueued) {
- isQueued = true;
- requestAnimationFrame(function() {
- cb.apply(context, args);
- isQueued = false;
- });
- }
- };
- };
- })(mui, window);
- (function($) {
- var initializing = false,
- fnTest = /xyz/.test(function() {
- xyz;
- }) ? /\b_super\b/ : /.*/;
- var Class = function() {};
- Class.extend = function(prop) {
- var _super = this.prototype;
- initializing = true;
- var prototype = new this();
- initializing = false;
- for (var name in prop) {
- prototype[name] = typeof prop[name] == "function" &&
- typeof _super[name] == "function" && fnTest.test(prop[name]) ?
- (function(name, fn) {
- return function() {
- var tmp = this._super;
- this._super = _super[name];
- var ret = fn.apply(this, arguments);
- this._super = tmp;
- return ret;
- };
- })(name, prop[name]) :
- prop[name];
- }
- function Class() {
- if (!initializing && this.init)
- this.init.apply(this, arguments);
- }
- Class.prototype = prototype;
- Class.prototype.constructor = Class;
- Class.extend = arguments.callee;
- return Class;
- };
- $.Class = Class;
- })(mui);
|