-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzMobile.js
executable file
·2284 lines (1985 loc) · 60.3 KB
/
zMobile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Created with JetBrains WebStorm.
* User: Zuobai
* Date: 13-8-9
* Time: 上午11:38
* To change this template use File | Settings | File Templates.
*/
(function () {
// region 浏览器检测
var ua = function ( ua, appVersion, platform ) {
var canTouch = ("ontouchstart" in document) || (window.DocumentTouch && document instanceof DocumentTouch);
if ( (/Chrome/gi).test( ua ) && (platform === "Win32") ) {
canTouch = false;
}
return {
// win系列
win32 : platform === "Win32",
ie : /MSIE ([^;]+)/.test( ua ),
ieMobile : window.navigator.msPointerEnabled,
ieVersion : Math.floor( (/MSIE ([^;]+)/.exec( ua ) || [0, "0"])[1] ),
// ios系列
ios : (/iphone|ipad/gi).test( appVersion ),
iphone : (/iphone/gi).test( appVersion ),
ipad : (/ipad/gi).test( appVersion ),
iosVersion : parseFloat( ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec( ua ) || [0, ''])[1])
.replace( 'undefined', '3_2' ).replace( '_', '.' ).replace( '_', '' ) ) || false,
safari : /Version\//gi.test( appVersion ) && /Safari/gi.test( appVersion ),
uiWebView : /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test( ua ),
// 安卓系列
android : (/android/gi).test( appVersion ),
androidVersion : parseFloat( "" + (/android ([0-9\.]*)/i.exec( ua ) || [0, ''])[1] ),
// chrome
chrome : /Chrome/gi.test( ua ),
chromeVersion : parseInt( (/Chrome\/([0-9]*)/gi.exec( ua ) || [0, 0])[1], 10 ),
// 内核
webkit : /AppleWebKit/.test( appVersion ),
// 其他浏览器
uc : appVersion.indexOf( "UCBrowser" ) !== -1,
Browser : / Browser/gi.test( appVersion ),
MiuiBrowser : /MiuiBrowser/gi.test( appVersion ),
// 微信
MicroMessenger : ua.toLowerCase().match( /MicroMessenger/i ) == "micromessenger",
// 其他
canTouch : canTouch
};
}( navigator.userAgent, navigator.appVersion, navigator.platform );
// endregion
// region 常量
var SwipeRadius = 5, // 扫半径
HMoveRatio = 0.5; // 横向移动比例
// 方向
var Direction = {
positive : true,
negative : false
};
// endregion
// region util
// 运行脚本
function run( str ) {
new Function( str )();
}
// 判断x是否在[a,b)或[b,a)区间内
function inRange( x, a, b ) {
if ( a <= b ) {
return x >= a && x < b;
}
else {
return inRange( x, b, a );
}
}
// 将x限制在[a,b]或[b,a]内
function range( x, a, b ) {
if ( a <= b ) {
return x < a ? a : x > b ? b : x;
}
else {
return range( x, b, a );
}
}
// 平方函数
function square( x ) {
return x * x;
}
// 循环
function loop( t, block ) {
for ( var i = 0; i !== t; ++i ) {
block( i );
}
}
// 遍历数组
function loopArray( list, block ) {
var retVal;
for ( var i = 0, len = list.length; i !== len; ++i ) {
if ( (retVal = block( list[i], i )) !== undefined ) {
return retVal;
}
}
}
// 提供数组的top
Object.defineProperty( Array.prototype, "top", {
get : function () {
return this[this.length - 1];
},
set : function ( val ) {
this[this.length - 1] = val;
}
} );
// 提供数组的删除和contains
Array.prototype.remove = function ( arg ) {
var retVal = [];
loopArray( this, function ( item ) {
is.Function( arg ) ? !arg( item ) && retVal.push( item ) : arg !== item && retVal.push( item );
} );
return retVal;
};
Array.prototype.contains = function ( arg ) {
for ( var len = this.length, i = 0; i !== len; ++i ) {
if ( is.Function( arg ) ? arg( this[i] ) : (this[i] === arg) ) {
return true;
}
}
return false;
};
// 遍历对象
function loopObj( obj, block ) {
for ( var key in obj ) {
block( key, obj[key] );
}
}
// 操作数组
function reduce( initValue, array, operate ) {
loopArray( array, function ( item, i ) {
var result = operate( initValue, item, i );
if ( result !== undefined ) {
initValue = result;
}
} );
return initValue;
}
// 使用handler处理数据,若未提供handler,返回未处理过的数据
function handleData( handler, data ) {
return handler ? handler.apply( null, Array.prototype.slice.call( arguments, 1 ) ) : data;
}
// 将一个元组转化为字符串
// 如TupleString( "rgba" )( 2, 3, 4, 0.4 )会返回rgba(2,3,4,0.4);
function TupleString( tupleName ) {
return function () {
return tupleName + "(" + Array.prototype.join.call( arguments, "," ) + ")";
};
}
var translate3d = TupleString( "translate3d" );
// 解析配对连接字符串,如name=tom&class=2&grade=3
function parsePairString( str, split1, split2, doPair ) {
loopArray( str.split( split1 ), function ( searchPair ) {
var keyValue = searchPair.split( split2 );
doPair( keyValue[0], keyValue[1] );
} );
}
// 判断对象类型
var is = reduce( {}, ["Array", "Boolean", "Date", "Function", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"], function ( is, typeName ) {
is[typeName] = function ( obj ) {
return Object.prototype.toString.call( obj ) == "[object " + typeName + "]";
};
} );
// 将一个对象插入到另一个对象,修改obj1
function insert( obj1, obj2 ) {
loopObj( obj2, function ( key, value ) {
obj1[key] = value;
} );
return obj1;
}
// 扩展对象,不修改它
function extend( obj1 ) {
var retVal = is.Array( obj1 ) ? [] : {};
loopArray( arguments, function ( val ) {
insert( retVal, val );
} );
return retVal;
}
// 设置参数的默认值
function defaultArg( arg, defaultArg ) {
return extend( defaultArg, arg || {} );
}
// 函数第一次被调用时执行回调
function firstCall( func, callback ) {
if ( !func.zFirstCall ) {
callback();
func.zFirstCall = true;
}
}
// 双向链表
function LinkedList() {
var head = null, tail = null;
var count = 0;
function addTail( value ) {
var node = Node( value );
node.previous = tail;
if ( tail === null ) {
head = node;
}
else {
tail.next = node;
}
tail = node;
return node;
}
function Node( value ) {
var node = {
previous : null,
next : null,
value : value,
remove : function () {
--count;
if ( node.previous !== null ) {
node.previous.next = node.next;
}
else {
head = node.next;
}
if ( node.next !== null ) {
node.next.previous = node.previous;
}
else {
tail = node.previous;
}
},
insertBefore : function ( value ) {
var newNode = Node( value );
newNode.previous = node.previous;
newNode.next = node;
node.previous = newNode;
if ( newNode.previous !== null ) {
newNode.previous.next = newNode;
}
else {
head = newNode;
}
return newNode;
},
insertAfter : function ( value ) {
return node.next === null ? addTail( value ) : node.next.insertAfter( value );
}
};
++count;
return node;
}
return {
addTail : addTail,
addHead : function ( value ) {
return head === null ? addTail( value ) : head.insertBefore( value );
},
head : function () {
return head;
},
tail : function () {
return tail;
},
count : function () {
return count;
}
};
}
LinkedList.loop = function ( list, func ) {
for ( var cur = list.head(); cur !== null; cur = cur.next ) {
func( cur.value, cur );
}
};
LinkedList.toArray = function ( list ) {
var arr = [];
LinkedList.loop( list, function ( value ) {
arr.push( value );
} );
return arr;
};
// 开关,可以添加一个回调,当开关切换时会调用回调
function Switcher( init, onSwitch, firstCut ) {
var isOpen;
function cut( val ) {
if ( val === undefined ) {
return isOpen;
}
else {
if ( isOpen !== val ) {
isOpen = val;
onSwitch( val );
}
}
}
firstCut && cut( init );
return cut;
}
// endregion
// region DOM
// 遍历节点
function loopNodeList( node, func, className ) {
if ( node && node.nextElementSibling !== undefined ) {
while ( node ) {
var nextNode = node.nextElementSibling;
className ? node.classList.contains( className ) && func( node ) : func( node );
node = nextNode;
}
}
else if ( node && node.length ) {
loopArray( node, func );
}
}
function bubble( el, func, root ) {
var retVal;
while ( el !== null && el !== document && el !== root ) {
if ( (retVal = func( el )) !== undefined ) {
return retVal;
}
el = el.parentNode;
}
}
function findAncestor( el, func ) {
var retVal = null;
bubble( el, function ( el ) {
if ( func( el ) ) {
return retVal = el;
}
} );
return retVal;
}
// 判断一个节点是否在文档内
function inDocument( el ) {
return findAncestor( el, function ( el ) {
return el === document.documentElement;
} ) === document.documentElement;
}
// 计算一个元素相对于文档的偏移
function CalculateElementDocumentOffset( offsetName ) {
return function ( el ) {
var retVal = 0;
for ( var cur = el; cur !== null; cur = cur.offsetParent ) {
retVal += cur[offsetName];
}
return retVal;
};
}
var getPageLeft = CalculateElementDocumentOffset( "offsetLeft" ), getPageTop = CalculateElementDocumentOffset( "offsetTop" );
// 移除节点
function removeNode( el ) {
el && el.parentNode && el.parentNode.removeChild( el );
}
// 根据pattern,移除class
function removeClass( el, pattern ) {
var matchedClass = [];
loopArray( el.classList, function ( className ) {
pattern.test( className ) && matchedClass.push( className );
} );
loopArray( matchedClass, function ( className ) {
el.classList.remove( className );
} );
}
// 加载脚本
function loadScript( scriptSrc, onLoad ) {
var script = document.createElement( "script" );
script.src = scriptSrc;
bindEvent( script, "load", onLoad );
document.head.appendChild( script );
return script;
}
// 切换状态
function toggleState( el, fromState, toState ) {
el.classList.remove( fromState );
el.classList.add( toState );
}
// 根据flag,添加或删除class
function switchClass( el, className, flag ) {
flag ? el.classList.add( className ) : el.classList.remove( className );
}
// 覆写appendChild,提供页脚功能
var appendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function ( el ) {
if ( this.hasAttribute( "data-zone" ) ) {
var footer = this.footer || (this.footer = this.querySelector( "[data-footer]" ));
footer ? this.insertBefore( el, footer ) : appendChild.call( this, el );
footer && footer.getAttribute( "data-on-append" ) && window[footer.getAttribute( "data-on-append" )]( this, el, footer );
}
else {
appendChild.call( this, el );
}
return el;
};
Node.prototype.appendChildren = function ( el ) {
var nodeList = el.childNodes, len = nodeList.length;
while ( len-- !== 0 ) {
this.appendChild( nodeList[0] );
}
return el;
};
// 抽取属性,抽取后将该属性删除
function extractAttribute( el, attrName ) {
var retVal = el.getAttribute( attrName );
el.removeAttribute( attrName );
return retVal;
}
// 遍历选择器
function loopSelector( parent, selector, func, child ) {
if ( parent === document ) {
loopArray( parent.querySelectorAll( selector ), func );
}
else {
var ancestor = parent.parentNode || element( "div", {
child : parent
} );
parent.setAttribute( "data-z", "" );
var nodeList = !child ? ancestor.querySelectorAll( selector + "[data-z], [data-z] " + selector ) :
ancestor.querySelectorAll( "[data-z] > " + selector );
parent.removeAttribute( "data-z" );
loopArray( nodeList, func );
}
}
// 根据属性处理元素
function doNodeByAttribute( root, attrName, func ) {
function doAttr( attrName ) {
loopSelector( root, "[" + attrName + "]", function ( node ) {
func( node, extractAttribute( node, attrName ), attrName );
} );
}
is.Array( attrName ) ? loopArray( attrName, doAttr ) : doAttr( attrName );
}
// 创建一个元素的快捷方式
function element( tagName, arg, parentNode ) {
function doClass( value ) {
if ( is.String( value ) ) {
el.classList.add( value );
}
else if ( is.Array( value ) ) {
loopArray( value, function ( className ) {
el.classList.add( className );
} );
}
}
var el = document.createElement( tagName );
if ( is.Object( arg ) ) {
loopObj( arg, function ( key, value ) {
if ( value !== undefined ) {
switch ( key ) {
case "classList":
doClass( value );
break;
case "css":
css( el, value );
break;
case "attr":
loopObj( el, function ( key, value ) {
el.setAttribute( key, value );
} );
break;
case "innerHTML":
el.innerHTML = value;
break;
case "src":
case "href":
case "title":
el.setAttribute( key, value );
break;
case "child":
if ( is.Array( value ) ) {
loopArray( value, function ( node ) {
el.appendChild( node );
} );
}
else {
el.appendChild( value );
}
break;
default:
if ( key.substring( 0, 5 ) === "data-" ) {
el.setAttribute( key, value );
}
break;
}
}
} );
}
else {
doClass( arg );
}
parentNode && parentNode.appendChild( el );
return el;
}
// HTML模板
function doHTML( parentNode, handlers, context ) {
// 处理字段对应的元素节点
loopSelector( parentNode, "*", function ( fieldNode ) {
loopObj( fieldNode.dataset, function ( key, value ) {
var handler = handlers[key];
if ( handler !== undefined ) {
handler( fieldNode, value, context );
fieldNode.removeAttribute( "data-" + key.replace( /([A-Z])/g, "-$1" ).toLowerCase() );
}
} );
} );
}
function HTMLTemplate( templateDiv ) {
var templates = {};
var handlers = {
field : function ( node, value, data ) {
var html = data[value];
node.innerHTML = html === undefined || html === null ? "" : html;
},
text : function ( node, value, data ) {
node.textContent = data[value];
},
src : function ( node, value, data ) {
node.setAttribute( "src", data[value] );
},
href : function ( node, value ) {
onTap( node, function () {
location.href = value;
} );
},
attr : function ( node, value, data ) {
parsePairString( value, " ", ":", function ( key, value ) {
node.setAttribute( key, data[value] );
} );
},
list : function ( node, value, data ) {
var keyValue = value.split( " " );
makeList( keyValue[0], keyValue[1] ? data[keyValue[1]] : data, node );
},
replace : function ( node, value, data ) {
var arg = value.split( " " );
data = arg[1] ? data[arg[1]] : data;
if ( data !== undefined ) {
node.parentNode.replaceChild( make( arg[0], data ), node );
}
else {
removeNode( node );
}
},
"class" : function ( node, value, data ) {
loopArray( value.split( " " ), function ( fieldName ) {
node.classList.add( data[fieldName] );
} );
},
lengthOf : function ( node, value, data ) {
node.innerHTML = value ? data[value].length : data.length;
},
length : function ( node, value, data ) {
node.innerHTML = data._length;
},
index : function ( node, value, data ) {
node.innerHTML = data._index + 1;
}
};
// 储存模板,并将模板移出DOM树
doNodeByAttribute( templateDiv, "data-template-id", function ( templateNode, templateId ) {
var mainNode = templateNode.querySelector( "[data-main]" ) || templateNode;
templates[templateId] = mainNode;
mainNode.removeAttribute( "data-main" );
} );
removeNode( templateDiv );
function make( templateID, data, apply ) {
var templateNode = templates[templateID];
var resultNode = templateNode.cloneNode( true );
doHTML( resultNode, handlers, data );
apply && apply( resultNode, data );
return resultNode;
}
function makeList( templateID, dataList, container, apply ) {
var len = dataList.length;
loopArray( dataList, function ( data, i ) {
var resultNode = make( templateID, extend( data, {
_index : i,
_length : len
} ), function ( node, data ) {
apply && apply( node, data, i );
} );
container && container.appendChild( resultNode );
} );
}
return {
make : make,
makeList : makeList,
addHandler : function ( val ) {
insert( handlers, val );
},
hasTemplate : function ( templateId ) {
return templates.hasOwnProperty( templateId );
},
handlers : function () {
return handlers;
}
};
}
// endregion
// region CSS
// 非标准样式
var nonstandardStyles = {
transform : ["-webkit-transform", "-ms-transform", "transform"],
transition : ["-webkit-transition", "transition"],
animation : ["-webkit-animation"],
"animation-play-state" : ["-webkit-animation-play-state"],
"backface-visibility" : ["-webkit-backface-visibility", "-mozila-backface-visibility", "backface-visibility"],
"transform-style" : ["-webkit-transform-style", "transform-style"],
perspective : ["-webkit-perspective", "perspective"]
};
// 设置CSS值,可以设置一条或者设置一组
function css( el, arg1, arg2 ) {
function setStyle( styleName, styleValue ) {
function doStyle( styleName ) {
styleValue !== null ? el.style.setProperty( styleName, styleValue, "" ) : el.style.removeProperty( styleName );
}
styleName in nonstandardStyles ? loopArray( nonstandardStyles[styleName], doStyle ) : doStyle( styleName );
}
is.String( arg1 ) ? setStyle( arg1, arg2 ) : loopObj( arg1, setStyle );
}
// 移除CSS值,可以移除一条,或者移除一组
function removeCss( el, styleName ) {
function removeStyle( styleName ) {
function doStyle( styleName ) {
el.style.removeProperty( styleName );
}
styleName in nonstandardStyles ? loopArray( nonstandardStyles[styleName], doStyle ) : doStyle( styleName );
}
is.String( styleName ) ? removeStyle( styleName ) : loopArray( styleName, removeStyle );
}
// 生成CSS样式字符串
function cssRuleString( cssStyles ) {
var ruleText = "";
loopObj( cssStyles, function ( styleName, styleValue ) {
function addRule( styleName ) {
ruleText += styleName + ":" + styleValue + ";";
}
styleName in nonstandardStyles ? loopArray( nonstandardStyles[styleName], addRule ) : addRule( styleName );
} );
return ruleText;
}
// 添加CSS规则
var insertCSSRule = function () {
var userSheet = LinkedList(), systemSheet = LinkedList();
return function ( ruleText, isSystem ) {
var styleSheet = isSystem ? systemSheet : userSheet; // 选择样式链表
// 如果节点尚未创建,创建节点,系统样式表在所有样式表的最前,用户样式表在所有样式表的最后
if ( styleSheet.node === undefined ) {
styleSheet.node = document.head.insertBefore( document.createElement( "style" ), isSystem ? document.head.firstChild : null );
}
// 创建新规则,位置上最后规则+1
var lastRule = styleSheet.tail(),
newRule = styleSheet.addTail( lastRule === null ? 0 : lastRule.value + 1 );
styleSheet.node.sheet.insertRule( ruleText, newRule.value );
return {
remove : function () {
// 后面所有元素的位置-1
var pos = newRule.value;
for ( var curNode = newRule.next; curNode !== null; curNode = curNode.next ) {
curNode.value = pos++;
}
// 移除节点并删除规则
newRule.remove();
styleSheet.node.sheet.deleteRule( pos );
}
};
}
}();
function insertCSSRules( arg1, arg2, arg3 ) {
function insertRules( selector, styles, isSystem ) {
insertCSSRule( selector + " {" + cssRuleString( styles ) + "}", isSystem );
}
if ( is.String( arg1 ) ) {
insertRules( arg1, arg2, arg3 );
}
else {
loopObj( arg1, function ( selector, styles ) {
insertRules( selector, styles, arg2 );
} );
}
}
// endregion
// region 事件
// 事件
function Event( basicTask ) {
var events = LinkedList();
return {
trig : function () {
var arg = arguments;
basicTask && basicTask.apply( null, arg ); // 回调基本事件
LinkedList.loop( events, function ( task ) {
task.apply( null, arg );
} );
},
regist : events.addTail
};
}
// 装载事件,装载成功后直接调用,装载成功前,排队等待调用
function LoadEvent() {
var isStartLoad = false, events = Event();
return {
regist : function ( task ) {
events === null ? task() : events.regist( task );
},
load : function ( loadFunc ) {
function loadDone() {
events.trig();
events = null;
}
!isStartLoad && (loadFunc === undefined ? loadDone() : loadFunc( loadDone ));
isStartLoad = true;
}
};
}
// 根据选择器,监听全局事件
function on( eventName, querySelector, response ) {
function match( node, nodes ) {
for ( var i = 0, len = nodes.length; i !== len; ++i ) {
if ( node === nodes.item( i ) ) {
return true;
}
}
return false;
}
document.addEventListener( eventName, function ( event ) {
var nodes = document.querySelectorAll( querySelector );
bubble( event.target, function ( node ) {
match( node, nodes ) && response && response( event, node );
}, document.body );
}, false );
}
function onBubble( eventName, response ) {
document.addEventListener( eventName, function ( event ) {
bubble( event.target, function ( node ) {
response( node );
}, document.documentElement );
}, false );
}
function bindEvent( el, eventName, response, isCapture ) {
el.addEventListener( eventName, response, isCapture === true );
return {
remove : function () {
el.removeEventListener( eventName, response, isCapture === true );
}
};
}
function onInsert( el, response ) {
if ( inDocument( el ) ) {
response && response();
}
else {
var insertEvent = bindEvent( el, "DOMNodeInsertedIntoDocument", function () {
response && response( el );
insertEvent.remove();
} );
}
}
// 取移动的事件坐标用
loopArray( ["pageX", "pageY", "clientX", "clientY"], function ( coordinateName ) {
Object.defineProperty( UIEvent.prototype, "z" + coordinateName.replace( /^./, function ( ch ) {
return ch.toUpperCase();
} ), {
get : function () {
return "touches" in this && this.touches[0] !== undefined ? this.touches[0][coordinateName] : this[coordinateName];
}
} );
} );
// touch事件绑定器
function TouchBind( IEEventName, OtherEventName, PCName ) {
return function ( el, response, isCapture ) {
return ua.canTouch ? bindEvent( el, window.navigator.msPointerEnabled ? IEEventName : OtherEventName, response ) :
bindEvent( el, PCName, response, isCapture );
};
}
var onTouchMove = TouchBind( "MSPointerMove", "touchmove", "mousemove" ),
onTouchEnd = TouchBind( "MSPointerUp", "touchend", "mouseup" ),
onTouchStart = function () {
var onTouchStart = TouchBind( "MSPointerDown", "touchstart", "mousedown" );
return function ( el, response, isCapture ) {
return onTouchStart( el, function ( event ) {
// 此次touch的move事件和end事件,这两个事件仅对于当次touch有效
var touchMoveEvent = Event(), touchEndEvent = Event();
var pageX = event.zPageX, pageY = event.zPageY;
var move = onTouchMove( document, function ( event ) {
pageX = event.zPageX;
pageY = event.zPageY;
// 将move事件和end事件的注册指令添加到event中
event.onTouchMove = touchMoveEvent.regist;
event.onTouchEnd = touchEndEvent.regist;
touchMoveEvent.trig( event, pageX, pageY );
} );
var end = onTouchEnd( document, function ( event ) {
touchEndEvent.trig( event, pageX, pageY );
move.remove();
end.remove();
} );
// 将move事件和end事件的注册指令添加到event中
event.onTouchMove = touchMoveEvent.regist;
event.onTouchEnd = touchEndEvent.regist;
// 回调response
response( event, pageX, pageY );
}, isCapture );
}
}();
// sense事件,根据触摸是否到达了阈值判断是否触发响应
function sense( el, senseFunc, arg ) {
return onTouchStart( el, function ( event, startX, startY ) {
arg.onSenseStart && arg.onSenseStart( event );
// sense事件,判断触摸移动是否到达sense阈值,若只是小幅移动,不触发响应
var senseTrue = false;
var senseEvent = event.onTouchMove( function ( event, pageX, pageY ) {
// 判断是否移动到了sense阈值,如果移动到了,停止判断,触发senseTrue响应
event.distanceX = pageX - startX;
event.distanceY = pageY - startY;
if ( senseFunc( event ) ) {
// 移除sense事件,不再侦测
senseEvent.remove();
senseTrue = true;
// 触发senseTrue响应
arg.onSenseTrue && arg.onSenseTrue( event, pageX, pageY );
}
} );
// 如果抬起的时候没有senseTrue,触发senseFalse响应
event.onTouchEnd( function ( event, pageX, pageY ) {
if ( !senseTrue ) {
arg.onSenseFalse && arg.onSenseFalse( event, pageX, pageY );
}
arg.onTouchEnd && arg.onTouchEnd();
} );
} );
}
// 一般的senser,判断是否超出圆
function senser( event ) {
return square( event.distanceX ) + square( event.distanceY ) > square( SwipeRadius );
}
// tap事件,轻触屏幕时(不引起sense)触发,在sense域时有class tap
function onTap( el, response, stopPropagation ) {
css( el, "cursor", "pointer" );
if ( window.voiceOver ) {
return bindEvent( el, "click", response );
}
else {
return sense( el, senser, {
onSenseTrue : function () {
el.classList.remove( "tap" );
},
onSenseFalse : function ( event, pageX, pageY ) {
!el.classList.contains( "disabled" ) && response && response( event, pageX, pageY );
},
onSenseStart : function ( event ) {
!el.classList.contains( "disabled" ) && el.classList.add( "tap" );
stopPropagation && event.stopPropagation();
},
onTouchEnd : function () {
el.classList.remove( "tap" );
}
} );
}
}
// 当摇晃屏幕时触发
function onShake( task, strength ) {
var lastTime = new Date();
var lastX = 0, lastY = 0, lastZ = 0, isFirst = true;
return Z.bindEvent( window, "devicemotion", function ( event ) {
var acceleration = event.accelerationIncludingGravity,
curTime = new Date();
if ( (curTime - lastTime) > 100 ) {
var diffTime = curTime - lastTime,
x = acceleration.x, y = acceleration.y, z = acceleration.z,
speed = isFirst ? 0 : Math.abs( x + y + z - lastX - lastY - lastZ ) / diffTime * 10000;
event.speed = speed;
if ( speed > 1000 * (strength || 1) ) {
task( event );
}
lastX = x;
lastY = y;
lastZ = z;
lastTime = curTime;
isFirst = false;
}
} );
}
// swipeStart事件,沿某一方向滑动某个阈值时触发
function SwipeStart( isHorizontal ) {
return function ( el, response, arg ) {