-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNL_02.js
1567 lines (1541 loc) · 61.7 KB
/
NL_02.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
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////
/////////////// 基础扩展
///////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @ target Extends the basic Javascript Language
* @ author peichao01
* @ date 2011-12-28
* @ last-change 2012-01-15 22:42 ------- 下一步,把 绑定事件 的事件对象,加上 命名空间,如:NL.on('box.click'); NL.on('toolbar.click'); NL.on('click');
*
* @ project ExtendsJs.js
* @ structor
************************* prototype ***************
****** String.trim
****** Array.forEach
****** Array.filter
****** Array.map
****** Array.indexOf
****** Function.bind
****** Function.method
****** Function.inherite
****** ****************** static method *************
****** Object.create
****** Object.construct
****** Object.merge
*/
/**
* @ target 去除参数字符串两侧的空字符
*
*/
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
}
/**
* @ target 遍历数组,为每一个元素执行一次指定的函数
* @ property fn: Function 对每个元素执行的函数
* @ property thisObj: Object (Alternative) 指定 this 对象
*
*/
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, thisObj) {
var scope = thisObj || window;
for (var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
};
}
/**
* @ target 使用指定的函数过滤数组元素,并把符合函数的元素组成新数组并返回
* @ property fn: Function 对每个元素执行的函数, 每个元素在函数中返回 true,则合格
* @ property thisObj: Object (Alternative) 指定 this 对象
* @ return new Array
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function (fn, thisObj) {
var scope = thisObj || window;
var a = [];
for (var i = 0, len = this.length; i < len; ++i) {
if (!fn.call(scope, this[i], i, this)) {
continue;
}
a.push(this[i]);
}
return a;
};
}
/**
* @ target 遍历数组,把每个元素在指定函数中执行的结果作为新的数组返回
* @ property fn: Function 对每个元素执行的函数
* @ property thisObj: Object (Alternative) 指定 this 对象
* @ return new Array 每个元素在指定函数中执行的结果
*/
if(!Array.prototype.map){
Array.prototype.map = function (fn, thisObj) {
if (typeof fn != "function")
throw new TypeError();
var scope = thisObj || window, result = [];
for (var i = 0, len = this.length; i < len; i++) {
if (i in this)
result[i] = fn.call(scope, this[i], i, this);
}
return result;
}
}
/**
* @ target 获取指定item在数组中的索引,如果不存在则返回-1
* @ property item: Mixin 要查找的item
* @ return index || -1: Int/Number
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (item) {
for (var i = 0, len = this.length; i < len; i++) {
if (item === this[i])
return i;
}
return -1;
}
}
/**
* @ target 移除数组中指定的元素,如果不存在则返回 false
* @ property item: Mixin 要移除的元素
* @ return index || -1 : Int/Number 移除的元素所在的索引位置
*/
if (!Array.prototype.remove) {
Array.prototype.remove = function (item) {
for (var i = 0, len = this.length; i < len; i++) {
if (item == this[i]) {
this.splice(i, 1);
return i;
}
}
return -1;
};
}
/**
* @ target 创建一个新的对象,并把参数作为新对象的原型
* @ property proto: Object 新对象的原型
* @ return new Object
*
* @ note 使用空函数 TempEmptyConstrctor 来做中间件,但这就扰乱了继承关系
* 重设新对象的 constructor 以重新指正正确的继承关系
*/
if(!Object.create){
Object.create = function (proto) {
var TempEmptyConstrctor = function () { };
TempEmptyConstrctor.prototype = proto;
var r = new TempEmptyConstrctor();
r.constructor = proto.constructor; //*** @ note
return r;
}
}
/**
* @ target 创建一个新的对象,把参数作为原型,且,若参数原型中含有 Main 函数,即先初始化 再返回
* @ property proto: Object 新对象的原型,且先初始化(若有 Main 函数)
* @ return new Object
*
* @ note 此方法的目的是把参数提供的对象作为原型生成新的对象
* 但在内部实现中,用到了第三方的一个空函数 TempEmptyConstrctor ,
* 这就扰乱了新对象的继承指示关系,最后重设新对象的 constructor 属性,
* 让新对象的 constructor 指向参数原型的 constructor,即它们应该是一条链继承下来的关系
*/
if(!Object.construct){
Object.construct = function (proto) {
var TempEmptyConstrctor = function () { };
if (proto.Main) {
proto.Main.apply(proto, [].slice.call(arguments, 1));
}
TempEmptyConstrctor.prototype = proto;
var r = new TempEmptyConstrctor();
r.constructor = proto.constructor; //*** @ note
return r;
}
}
/**
* @ target 合并对象,把source的属性都传递给接受的对象并返回
* @ property destination: Object 接受属性的对象
* @ property source: Object 输出属性的对象
* @ property isOverride: Boolean 接受者已经有了同名属性时,是否覆盖
*/
if (!Object.merge) {
Object.merge = function (destination, source, isOverride) {
for (var key in source) {
if (isOverride || !destination[key])
destination[key] = source[key];
}
}
}
/**
* @ version Mozilla 实现版
* @ target 为函数绑定 this 对象
* @ property thisObj: Object 需要绑定的 函数的 this指向
*
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (thisObj) {
if (typeof this !== "function")
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () { },
fBound = function () {
return fToBind.apply(this instanceof fNOP ? this : thisObj || window, aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/** bind @ version 简化版
if (!Function.prototype.bind) {
Function.prototype.bind = function (sourceObj) {
var arr = [], args = arr.slice.call(arguments, 1);
return function () {
return this.apply(sourceObj, arr.concat.apply(args, arr.slice.call(arguments,1)));
}
}
}
*/
/**
* @ target 为 函数 添加原型方法
* @ property fnName: String 方法的名字
* @ property fn: Function 方法函数本身
*
*/
if (!Function.prototype.method) {
Function.prototype.method = function (fnName, fn) {
this.prototype[fnName] = fn;
return this;
}
}
/**
* @ target 为 函数||类 添加原型
*
*/
if (!Function.prototype.addProto) {
Function.prototype.addProto = function (prototypes) {
for (var key in prototypes) {
this.prototype[key] = prototypes[key];
}
}
}
/**
* @ target 为 函数 添加静态方法 || 类方法 Fn.fn();
* @ property fnName: String 方法的名字
* @ property fn: Function 方法函数本身
* @ e.g.
* 1. function.addStaticFn('eat', fn);
* 2. function.addStaticFn({ eat: fn, sleep: fn2 });
*
*/
if (!Function.prototype.addStatic) {
Function.prototype.addStatic = function (staticThings) {
for (var key in staticThings) {
this[key] = staticThings[key];
}
return this;
}
}
/**
* @ target 继承自其它构造器
* @ property Class: Function 需要继承的父类构造函数
*
* @ note 继承之后,再把constructor重置回来
*
*/
if(!Function.prototype.inherite){
Function.prototype.inherite = function (Class) {
if (typeof Class != 'function')
throw new TypeError('custom: argument Class should be a Function.');
this.prototype = new Class();
this.prototype.constructor = this;//*** @ note
}
}
/**
* @ require ExtendJs.js
* @ means NL Naruto & Luffy
* @ author peichao01
* @ date 2011-12-28
* @ last-change 2012-01-13 23:01
* @ project Lib.js
* @ structor
****** NL.$
****** NL.$$: sizzle
****** NL.create
****** NL.onDomReady
******
****** NL.Browser
****** NL.Cookie
****** NL.Elements
****** NL.CSS
****** NL.ajax
****** NL.JSON
****** NL.Events
****** NL.Utils
****** NL.console
*/
(function (win, undefined) {
var doc = win.document, docEl = doc.documentElement,
isTagReg = /<\w+.*>/;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////
/////////////// NL 核心
///////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var _NL = (function(){
var $ = function(selector, context){
return new $.fn.init(selector, context);
}
$.addProto({
init: function(selector, context, results, seed){
if(!NL.$) throw new Error('custom : must load NL_sizzle.js first!');
if(selector.nodeType !== undefined) this.doms = new Array(selector);//如果传进来的是一个Element
else if(staticMethod.utils.isArray(selector) && selector[0].nodeType!==undefined) this.doms = selector;
else if(isTagReg.test(selector)) this.doms = staticMethod.elements.create(selector);
else this.doms = NL.$(selector, context);
},
doms : null
});
$.fn = $.prototype;
$.fn.init.prototype = $.fn;
return $;
})();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////
/////////////// NL 类的静态方法
///////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var staticMethod = {
/**
* @ target 创建一个类的实例
* @ property className: Function 类名/构造函数
* @ property [ Main's params: Mixin ] 此类 Main 函数的参数
* @ e.g.
* var instance = NL.create(ClassName, constructorParams);
*/
create: function (className, MainParams) {
var instance = (typeof className === 'function') ? (new className()) : (eval('new ' + className));
var args = [].slice.call(arguments, 1);
args.unshift(instance);
return Object.construct.apply(win, args);
},
elements: {
/**
* @ target 创建节点
* @ property TagOrHtml : String
* 1. 含有'<..>'的,认为是HTML字符串
* 2. 其余的,认为是 tag 标签名
* @ return Element || Array[ EL, EL... ]
* @ e.g.
* create('div');
* create('<div>content</div>');
*/
// NL('<div>..</div>') 是一个简化版的 create
create: function (TagOrHtml) {
if (isTagReg.test(TagOrHtml)) {
var div = this.create('div');
div.innerHTML = TagOrHtml;
var c = this.getChildren(div); div = null;
return c;
} else {
return document.createElement(TagOrHtml);
}
},
/*
* @ target 判断是否是 空白文本节点
*/
isWhiteTextNode: function (node) {
return node.nodeType === 3 && /^\s*$/.test(node.nodeValue);
},
/**
* @ target 获取 dom 元素的第 index 个子元素
* @ property dom: Element
* @ property index: Number
* @ property notCareTextNode : Boolean
* @ return child : Element
*/
getChild: function (dom, index, notCareTextNode) {
var ch = this.getChildren(dom, !notCareTextNode);
return staticMethod.utils.getItem(ch,index);
},
/**
* @ target 获取 dom 元素的所有子节点
* @ property dom: Element
* @ property keepTextNode = true : Boolean 是否保留 文本节点元素(nodeType == 3)|| 默认 true
* @ return children : Array
*/
getChildren: function (dom, keepTextNode) {
if (keepTextNode == undefined) keepTextNode = true;
var children = (function (self) {
var c = dom.childNodes, len = c.length, kt = keepTextNode, t = [], j = 0;
for (i = 0; i < len; i++) {
/*
* 因为空白文本节点 是毫无用处的,所以,此函数永远会过滤掉它
* 如果不保留文本节点,则要筛选 nodeType 是否 为 3
* 如果保留,则,同时判断 是否是空白的文本节点
*/
if (!kt && c[i].nodeType !== 3) {
t[j] = c[i];
j++;
} else if (kt && !self.isWhiteTextNode(c[i])) {
t[j] = c[i];
j++;
}
}
return t;
})(this);
return children;
},
/**
* @ target 获取第一个非text元素的子元素
* @ property dom: Element
* @ return dom: Element
*/
firstChild: function (dom) {
return (this.getChildren(dom))[0];
},
lastChild: function (dom) {
var c = this.getChildren(dom);
return c[c.length - 1];
},
prevElement: function (dom) {
var p = dom.previousSibling;
return n===null ? n : (this.isWhiteTextNode(p) ? arguments.callee(p) : p);
},
nextElement: function (dom) {
var n = dom.nextSibling;
return n===null ? n : (this.isWhiteTextNode(n) ? arguments.callee(n) : n);
},
/**
* @ target 获取参数节点的兄弟节点
* @ property dom: Element 要查看的元素
* @ property [ options: Object ]
* {
* tagName: tagName, //只在标签都为此tagName的元素中选择
* className: className //只在类名都为此className的元素中选择
* }
*
* @ note 在遇到 script 标签时,有错误:无法获取 script 标签下面的兄弟节点
*
* @ return siblings: Array
*/
getUsBrothers: function (dom, options) {
options = options || {};
var pa = dom.parentNode,
children = this.getChildren(pa),
tag = options.tagName,
cls = options.className,
i = 0, j = 0;
if (tag) {
var temp = [];
for (i = 0, j = 0, len = children.length; i < len; i++) {
if (children[i].tagName.toLowerCase() === tag.toLowerCase()) {
temp[j] = children[i];
j++;
}
}
children = temp;
}
if (cls) {
var temp = [];
for (i = 0, j = 0; i < children.length; i++) {
if (NL.CSS.hasClass(children[i], cls)) {
temp[j] = children[i];
j++;
}
}
children = temp;
}
return children;
},
getSiblings: function (dom, options) {
var siblings = this.getUsBrothers(dom, options);
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] === dom)
break;
}
siblings.splice(i, 1);
return siblings;
},
/**
* @ target 获取参数节点在兄弟节点是第几个元素
* @ property dom: Element 要查看的元素
* @ property [ options: Object ]
* {
* tagName: tagName, //只在标签都为此tagName的元素中定位索引
* className: className //只在类名都为此className的元素中定位索引
* }
*
* @ note 在遇到 script 标签时,有错误:无法获取 script 标签下面的兄弟节点
*
* @ return index: String
*/
getIndex: function (dom, options) {
var siblings = this.getUsBrothers(dom, options);
return staticMethod.utils.getIndex(dom, siblings);
},
/**
* @ target 检查是否是祖先节点
* @ property childEl: Element 需要检查的子节点
* @ property forefatherEl: Element (可能的)参数1的祖先节点
*/
isChildNode: function (childEl, parentsEl) {
if (childEl === win || childEl === doc)
throw new TypeError('custom: the first argument must be a child Element of document.');
while (childEl.parentNode !== doc) {
if (parentsEl === childEl)
return true;
childEl = childEl.parentNode;
}
return false;
},
/**
* @ target 往节点的末尾追加内容
* @ property El_Arr_Html: Element || Array || String
* 1. 含有 '<..>' 的字符串
* 2. 数组 [ El, '<div>..</div>', El... ]
* 3. Element 元素
*/
append: function (dom, El_Arr_Html) {
this.insert(dom, El_Arr_Html);
},
/**
* @ target 往节点的首部追加内容
* @ property ElementOrHtmlString: Element || String
*/
prepend: function (dom, El_Arr_Html) {
this.insert(dom, El_Arr_Html, 0);
},
/*
* @ target 往 dom 节点中第 index 位插入子节点
*
* @ note 此为基础方法,常用的为 prepend || append 往首部和末尾追加元素
*
* @ property dom : Element
* @ property El_Arr_Html: Element || Array || String
* 1. 含有 '<..>' 的字符串
* 2. 数组 [ El, '<div>..</div>', El... ]
* 3. Element 元素
* @ property index: Number 要插入的位置 || 如果省略,为 undefined,则在末尾追加,相当于 appendChild
* @ e.g.
* insert(dom, '<div>1</div>2<b>o3</b>', 2);
* insert(dom, ['div'], 0);
* insert(dom, El);
*/
insert: function (dom, El_Arr_Html, index) {
if (staticMethod.utils.isString(El_Arr_Html)) {
var c = this.create(El_Arr_Html);
this.insert(dom, c, index);
} else if (staticMethod.utils.isArray(El_Arr_Html)) {
for (var i = 0, len = El_Arr_Html.length; i < len; i++) {
index === undefined ? this.insert(dom, El_Arr_Html[i]) : this.insert(dom, El_Arr_Html[i], index + i);
}
} else {
if (staticMethod.utils.isNumber(index)) {
var f = this.getChild(dom, index);
dom.insertBefore(El_Arr_Html, f);
} else if (index === undefined) {
dom.insertBefore(El_Arr_Html);
}
}
}
},
/**
* @ target 判断DOM加载完毕
* @ property callback
* @ property enableFF2 [optional] 设置是否在FF2下使用DOMContentLoaded(在FF2下的特定场景有Bug)
* @ url http://varnow.org/?p=77 //参考来源
*/
onDomReady: function (callback, enableFF2) {
var isReady = false;
function doReady() {
if (isReady) return;
//确保onready只执行一次
isReady = true;
callback();
}
if (this.browser.isIE) {
(function () {
if (isReady) return;
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 0);
return;
}
doReady();
})();
NL.Events.on(win, 'load', doReady);
} else if (this.browser.isWebkit && this.browser.webkitVersion < 525) {
(function () {
if (isReady) return;
if (/load|complete/.test(document.readyState))
doReady();
else
setTimeout(arguments.callee, 0);
})();
NL.Events.on(win, 'load', doReady);
} else {
if (!this.browser.isFF || this.browser.version != 2 || enableFF2) {
NL.Events.on(doc, 'DOMContentLoaded', function (e) {
NL.Events.off(doc, 'DOMContentLoaded', arguments.callee);
doReady();
});
}
NL.Events.on(win, 'load', doReady);
}
},
/**
* @ target 浏览器的信息
* @
*/
browser: (function () {
var ua = navigator.userAgent,
isIE = (/MSIE/gi).test(ua),
isOpera = (/Opera/gi).test(ua),
isChrome = (/Chrome/gi).test(ua),
isWebkit = (/WebKit/gi).test(ua),
isSafari = (/Safari/gi).test(ua) && !isChrome,
isFF = (/Firefox/gi).test(ua),
version = (function () {
var v = 0;
if (isIE)
v = parseFloat(ua.substring(ua.indexOf('MSIE') + 4));
else if (isFF)
v = parseFloat(ua.substring(ua.indexOf('Firefox/') + 8));
else if (isOpera)
v = parseFloat(ua.substring(ua.indexOf('Opera/') + 6));
else if (isChrome)
v = parseFloat(ua.substring(ua.indexOf('Chrome/') + 7));
else if (isSafari)
v = parseFloat(ua.substring(ua.indexOf('Version/') + 8));
return v;
})(),
webkitVersion = isWebkit ? parseFloat(ua.substring(ua.indexOf('AppleWebKit/') + 12)) : false;
return {
ua: ua,
isIE: isIE,
isFF: isFF,
isWebkit: isWebkit,
isChrome: isChrome,
isSafari: isSafari,
isOpera: isOpera,
version: version,
webkitVersion: webkitVersion
};
})(),
/**
* @ target 管理cookie
*
* @ method setCookie
* @ method getCookie
* @ method killCookie
*/
cookie: {
DEFAULT_HOURS: 24,
setCookie: function (name, value, hours, path, domain, secure) {
if (typeof (hours) != 'number') {
hours = this.DEFAULT_HOURS;
}
var numHours = (new Date((new Date()).getTime() + hours * 3600000)).toGMTString();
document.cookie = name + '=' + escape(value) + ((numHours) ? (';expires=' + numHours) : '') + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure && (secure == true)) ? '; secure' : '');
},
getCookie: function (name) {
if (document.cookie == '') {
return false;
} else {
var firstChar, lastChar;
var theBigCookie = document.cookie;
firstChar = theBigCookie.indexOf(name);
if (firstChar != -1) {
firstChar += name.length + 1;
lastChar = theBigCookie.indexOf(';', firstChar);
if (lastChar == -1) lastChar = theBigCookie.length;
return unescape(theBigCookie.substring(firstChar, lastChar));
} else {
return false;
}
}
},
killCookie: function (name, path, domain) {
var theValue = this.getCookie(name);
if (theValue) {
document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '');
}
}
},
ajax : function (method, url, callback, data) {
method = method.toUpperCase();
var xhr = (function () {
try {
var tempXhr = new XMLHttpRequest();
xhr = new XMLHttpRequest(); // *** @ note
} catch (e) {
var tempXhr = new ActiveXObject('msxml2.xmlhttp.3.0');
xhr = new ActiveXObject('msxml2.xmlhttp.3.0');
}
return tempXhr;
})();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText, xhr.responseXML);
}
}
xhr.open(method, url, true);
if (method == 'GET') {
url = dataToUrl(data || {}, url);
data = null;
} else if (method == 'POST') {
data = dataToUrl(data);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//xhr.setRequestHeader('Content-length', data.length);
//xhr.setRequestHeader('Connection', 'close');
}
xhr.send(data);
/*
* @ target get请求时,把data对象添加到 url 的末尾
* @ property url: String URL
* @ property data: Object 请求参数
*/
function dataToUrl(data, url) {
if (url) {
url += url.indexOf('?') == -1 ? '?' : '';
} else {
url = '';
}
for (var key in data) {
url += key + '=' + data[key] + '&';
}
return url.substring(0, url.length - 1);
}
},
JSON : {
/**
* @ target 把JSON字符串解析为json字面值
* @ note 目前得到的 Number Boolean RegExp Date 都是 String, 在使用时需要二次转换(IE)
*/
parse: function (jsonStr) {
/*if (win.JSON && JSON.parse) {
return win.JSON.parse(jsonStr);
} else {*/
try {
var temp = win.JSON.parse(jsonStr);
} catch (e) {
eval('var temp = ' + jsonStr);
}
return temp;
},
/**
* @ target 把json字面值转换为JSON字符串
* @ note 目前可以正常转换 String Number Boolean Object Array RegExp Date
* @ e.g. NL.JSON.stringify(['hello', 50, true, { name: 'John', age: 23, reg: /a/g, arr: ['shit', new Date()]}]);
*/
stringify: function (javascriptObjectNotation) {
if (win.JSON && JSON.stringify) {
return win.JSON.stringify(javascriptObjectNotation);
} else {
var change = (function (s) {
var result = '';
if (staticMethod.utils.isArray(s)) {
result += '[';
for (var i = 0, len = s.length; i < len; i++) {
result += arguments.callee(s[i]) + ',';
}
result = result.substr(0, result.length - 1);
result += ']';
} else if (staticMethod.utils.isOriginObject(s)) {
result += '{';
for (var key in s) {
result += '"' + key + '"' + ':' + arguments.callee(s[key]) + ',';
}
result = result.substr(0, result.length - 1);
result += '}';
} else {
result += '"' + s.toString() + '"';
}
return result;
})(javascriptObjectNotation);
//return "'" + change + "'";
return change;
}
}
},
utils : {
/**
* @ target 转换驼峰格式到连线格式
* @ e.g. 'myNameIs'' --> 'my-name-is
*/
toHyphens: function (camelCaseValue) {
var result = camelCaseValue.replace(/[A-Z]/g, function (character) {
return ('-' + character.charAt(0).toLowerCase());
});
return result;
},
/**
* @ target 转换连线格式到驼峰格式
* @ e.g. 'my-name-is' --> 'myNameIs'
*/
toCamelCase: function (hyphenatedValue) {
return hyphenatedValue.replace(/-([a-z])/g, function (m, w) {
return m.slice(1).toUpperCase();
});
},
/**
* @ target 替换字符串中特定的 元素
* @ property text: String 需要替换的字符串
* @ property values: Object 被替换的键值对
* @ e.g. ('my name is {name}, and age is {age}', {name:"peichao", age:23})
*/
replaceText: function (text, values) {
for (var key in values) {
if (values.hasOwnProperty(key)) {
if (typeof values[key] == undefined) {
values[key] = '';
}
text = text.replace(new RegExp("{" + key + "}", "g"), values[key]);
}
}
return text;
},
$_GET: function (name) {
},
/*
* @ target 获取数组中指定index的元素
*/
getItem: function (array, index) {
return array.splice(index, 1)[0];
},
isInArray: function (item, array) {
return this.getIndex(item, array) === -1 ? false : true;
},
getIndex: function(item, array){
for (var i = 0, len = array.length; i < len; i++) {
if (item === array[i])
return i;
}
return -1;
},
toRealArray: function (fakeArray) {
try {
return Array.prototype.slice.call(fakeArray);
} catch (e) {
var f = fakeArray, len = f.length, t = new Array(len);
for (var i = 0; i < len; i++) {
t[i] = f[i];
}
return t;
}
},
/**
* @ target 返回指定参数的数据类型
*
*
*/
getType: function (sth) {
var str = Object.prototype.toString.call(sth);
return str.substring(8, str.length - 1);
},
isString: function (sth) {
return this.getType(sth) === 'String';
},
isNumber: function (sth) {
return this.getType(sth) === 'Number';
},
isBoolean: function (sth) {
return this.getType(sth) === 'Boolean';
},
isArray: function (sth) {
return this.getType(sth) === 'Array';
},
isOriginObject: function (sth) {
return this.getType(sth) === 'Object';
},
isFunction: function(sth){
return this.getType(sth) === 'Function';
},
isRegExp: function (sth) {
return this.getType(sth) === 'RegExp';
},
isDate: function (sth) {
return this.getType(sth) === 'Date';
},
isUndefined: function(sth){
return sth === undefined;
},
isNull: function(sth){
return sth === null;
},
/**
* @ target 返回当前时间的标准格式
* @ return 2012-1-11 23:01:25
*/
getFullDate: function () {
var d = new Date(),
da = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate(),
t = d.toString().substring(16, 24);
return da + ' ' + t;
},
/**
* @ target 返回当前时间的标准格式
* @ return 23:01:25
*/
getStdTime: function () {
var date = this.getFullDate();
return date.substring(date.indexOf(' ') + 1);
},
/**
* @ target 返回当前时间的标准格式
* @ return 2012-1-11
*/
getStdDate: function () {
var date = this.getFullDate();
return date.substring(0, date.indexOf(' '));
}
},
console : {
_log: function(msg, full){
if (win.console && console.log && !full) {
console.log(msg);
}else{
var dom = doc.getElementById('$$console');
if (!dom) {
dom = document.createElement('div');
dom.setAttribute('id', '$$console');
NL.CSS.setStyle(dom, {
'border-top': '2px solid #666',
'background-color': '#eee',
'position': 'absolute',
'bottom': '0',
'left': '0',
'overflow': 'auto',
'height': '100px',
'width': '100%',
'margin': '0',
'padding': '0'
});
document.body.appendChild(dom);
};
var p = document.createElement('p');
NL.CSS.setStyle(p, {
'border-bottom': '1px solid #aaa',
'font-size': '12px',
'line-height': '180%',
'height': '20px',
'margin': '0',
'padding': '0'
});
dom.appendChild(p);
p.innerHTML = msg;
}
},
log: function (obj, full) {
if (win.console && console.log && !full) {
console.log(obj);
} else if (staticMethod.utils.isOriginObject(obj)) {
for (var key in obj) {
NL.console._log(key + ' : ' + obj[key], full);
}
} else {
NL.console._log(obj, full);
}
},
setHeight: function (height) {
if (!win.console) {
var dom = doc.getElementById('$$console');
if (!dom)
NL.console.log('');
NL.CSS.setStyle(dom, {
'height': height + 'px'
});
}
},
clear: function () {
doc.getElementById('$$console').innerHTML = '';
}
}
};
/**
* @ target Event Bus 事件管理 non-DOM
* @ method on(listen) --------------- 监听事件的方法
* @ method off(remove|removeAll) ---- 移除事件的方法
* @ method fire --------------------- 发出事件
*
* @ note ---------------------------- DOM 事件 见 NL() 的实例方法
*/
var staticMethod_events = new function(){
var events = {};
/*
* @ target non-DOM 的监听事件的方法
* @ property eventType: String 监听的事件类型
* @ property callback: Function 监听的事件
*
* e.g.
* NL.on('customEvent', fn);
* NL.on({ 'customEvent': fn, 'loaded': fn2 })
*
* @ return ID: Array
*