forked from RubyLouvre/avalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavalon.js
3675 lines (3533 loc) · 151 KB
/
avalon.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
//==================================================
// avalon 0.98 by 司徒正美 2013.10.21
// 疑问:
// 什么协议? MIT, (五种开源协议的比较(BSD,Apache,GPL,LGPL,MIThttp://www.awflasher.com/blog/archives/939)
// 依赖情况? 没有任何依赖,可自由搭配jQuery, mass等使用,并不会引发冲突问题
//==================================================
(function(DOC) {
var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
var expose = new Date - 0
var subscribers = "$" + expose
var otherRequire = window.require
var otherDefine = window.define
var stopRepeatAssign = false
var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
var class2type = {}
var oproto = Object.prototype
var ohasOwn = oproto.hasOwnProperty
var prefix = "ms-"
var W3C = window.dispatchEvent
var root = DOC.documentElement
var serialize = oproto.toString
var aslice = [].slice
var head = DOC.head || DOC.getElementsByTagName("head")[0] //HEAD元素
var documentFragment = DOC.createDocumentFragment()
var DONT_ENUM = "propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor".split(",")
"Boolean Number String Function Array Date RegExp Object Error".replace(rword, function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
var rnative = /\[native code\]/
var rchecktype = /^(?:object|array)$/
var rwindow = /^\[object (Window|DOMWindow|global)\]$/
function noop() {
}
function log(a) {
window.console && console.log(W3C ? a : a + "")
}
/*********************************************************************
* 命名空间 *
**********************************************************************/
avalon = function(el) { //创建jQuery式的无new 实例化结构
return new avalon.init(el)
}
avalon.init = function(el) {
this[0] = this.element = el
}
avalon.fn = avalon.prototype = avalon.init.prototype
//率先添加三个判定类型的方法
function getType(obj) { //取得类型
if (obj == null) {
return String(obj)
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === "object" || typeof obj === "function" ?
class2type[serialize.call(obj)] || "object" :
typeof obj
}
avalon.type = getType
avalon.isWindow = function(obj) {
if (!obj)
return false
// 利用IE678 window == document为true,document == window竟然为false的神奇特性
// 标准浏览器及IE9,IE19等使用 正则检测
return obj == obj.document && obj.document != obj
}
function isWindow(obj) {
return rwindow.test(serialize.call(obj))
}
if (isWindow(window)) {
avalon.isWindow = isWindow
}
//判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例。
avalon.isPlainObject = function(obj) {
if (getType(obj) !== "object" || obj.nodeType || this.isWindow(obj)) {
return false
}
try {
if (obj.constructor && !ohasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false
}
} catch (e) {
return false
}
return true
}
if (rnative.test(Object.getPrototypeOf)) {
avalon.isPlainObject = function(obj) {
return obj && typeof obj === "object" && Object.getPrototypeOf(obj) === oproto
}
}
avalon.mix = avalon.fn.mix = function() {
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[1] || {}
i++
}
//确保接受方为一个复杂的数据类型
if (typeof target !== "object" && getType(target) !== "function") {
target = {}
}
//如果只有一个参数,那么新成员添加于mix所在的对象上
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 && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && Array.isArray(src) ? src : []
} else {
clone = src && avalon.isPlainObject(src) ? src : {}
}
target[name] = avalon.mix(deep, clone, copy)
} else if (copy !== void 0) {
target[name] = copy
}
}
}
}
return target
}
var eventMap = avalon.eventMap = {}
function resetNumber(a, n, end) { //用于模拟slice, splice的效果
if ((a === +a) && !(a % 1)) { //如果是整数
if (a < 0) {
a = a * -1 >= n ? 0 : a + n
} else {
a = a > n ? n : a
}
} else {
a = end ? n : 0
}
return a
}
function oneObject(array, val) {
if (typeof array === "string") {
array = array.match(rword) || []
}
var result = {},
value = val !== void 0 ? val : 1
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value
}
return result
}
avalon.mix({
rword: rword,
subscribers: subscribers,
ui: {},
log: log,
slice: W3C ? function(nodes, start, end) {
return aslice.call(nodes, start, end)
} : function(nodes, start, end) {
var ret = [],
n = nodes.length;
start = resetNumber(start, n)
end = resetNumber(end, n, 1)
for (var i = start; i < end; ++i) {
ret[i - start] = nodes[i]
}
return ret
},
noop: noop,
error: function(str, e) { //如果不用Error对象封装一下,str在控制台下可能会乱码
throw new (e || Error)(str)
},
oneObject: oneObject,
/* avalon.range(10)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
avalon.range(1, 11)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
avalon.range(0, 30, 5)
=> [0, 5, 10, 15, 20, 25]
avalon.range(0, -10, -1)
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
avalon.range(0)
=> []*/
range: function(start, end, step) { // 用于生成整数数组
step || (step = 1)
if (end == null) {
end = start || 0
start = 0
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = Array(length)
while (++index < length) {
result[index] = start
start += step
}
return result
},
bind: function(el, type, fn, phase) { // 绑定事件
function callback(e) {
if (!e.target) {
fixEvent(e)
}
var ret = fn.call(el, e)
if (ret === false) {
e.preventDefault()
e.stopPropagation()
}
return ret
}
if (W3C) { //addEventListener对return false不做处理,需要自己fix
el.addEventListener(eventMap[type] || type, callback, !!phase)
} else {
try {
el.attachEvent("on" + type, callback)
} catch (e) {
}
}
return callback
},
unbind: W3C ? function(el, type, fn, phase) { //卸载事件
el.removeEventListener(eventMap[type] || type, fn || noop, !!phase)
} : function(el, type, fn) {
el.detachEvent("on" + type, fn || noop)
},
css: function(node, name, value) {
if (node instanceof avalon) {
var that = node
node = node[0]
}
var prop = /[_-]/.test(name) ? camelize(name) : name
name = avalon.cssName(prop) || prop
if (value === void 0 || typeof value === "boolean") { //获取样式
var fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
var val = fn(node, name)
return value === true ? parseFloat(val) || 0 : val
} else if (value === "") { //请除样式
node.style[name] = ""
} else { //设置样式
if (value == null || value !== value) {
return;
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += "px"
}
fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
fn(node, name, value)
}
return that
}
})
//视浏览器情况采用最快的异步回调
var BrowserMutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (BrowserMutationObserver) { //chrome18+, safari6+, firefox14+,ie11+,opera15
avalon.nextTick = function(callback) { //2-3ms
var input = DOC.createElement("input")
var observer = new BrowserMutationObserver(function(mutations) {
mutations.forEach(function() {
callback()
})
})
observer.observe(input, {
attributes: true
})
input.setAttribute("value", Math.random())
}
} else if (window.VBArray) { //IE下这个通常只要1ms,而且没有副作用,不会发现请求,setImmediate如果只执行一次,与setTimeout一样要140ms上下
avalon.nextTick = function(callback) {
var node = DOC.createElement("script")
node.onreadystatechange = function() {
callback() //在interactive阶段就触发
node.onreadystatechange = null
root.removeChild(node)
node = null
}
root.appendChild(node)
}
} else {
avalon.nextTick = function(callback) {
setTimeout(callback, 0)
}
}
var VMODELS = avalon.vmodels = {}
//只让节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象通过
function isArrayLike(obj) {
if (obj && typeof obj === "object") {
var n = obj.length
if (+n === n && !(n % 1) && n >= 0) { //检测length属性是否为非负整数
try {
if ({}.propertyIsEnumerable.call(obj, 'length') === false) { //如果是原生对象
return Array.isArray(obj) || /^\s?function/.test(obj.item || obj.callee)
}
return true;
} catch (e) { //IE的NodeList直接抛错
return true
}
}
}
return false
}
function generateID() {
//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
return "avalon" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
avalon.each = function(obj, fn) {
if (obj) { //不能传个null, undefined进来
var i = 0
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
fn(i, obj[i])
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
fn(i, obj[i])
}
}
}
}
}
/*********************************************************************
* ecma262 v5语法补丁 *
**********************************************************************/
if (!"司徒正美".trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, '')
}
}
for (var i in {
toString: 1
}) {
DONT_ENUM = false
}
if (!Object.keys) {
Object.keys = function(obj) { //ecma262v5 15.2.3.14
var result = []
for (var key in obj)
if (obj.hasOwnProperty(key)) {
result.push(key)
}
if (DONT_ENUM && obj) {
for (var i = 0; key = DONT_ENUM[i++]; ) {
if (obj.hasOwnProperty(key)) {
result.push(key)
}
}
}
return result
}
}
if (!Array.isArray) {
Array.isArray = function(a) {
return a && getType(a) === "array"
}
}
if (!noop.bind) {
Function.prototype.bind = function(scope) {
if (arguments.length < 2 && scope === void 0)
return this
var fn = this,
argv = arguments
return function() {
var args = [],
i
for (i = 1; i < argv.length; i++)
args.push(argv[i])
for (i = 0; i < arguments.length; i++)
args.push(arguments[i])
return fn.apply(scope, args)
}
}
}
function iterator(vars, body, ret) {
var fun = 'for(var ' + vars + 'i=0,n = this.length; i < n; i++){' + body.replace('_', '((i in this) && fn.call(scope,this[i],i,this))') + '}' + ret
return Function("fn,scope", fun)
}
if (!rnative.test([].map)) {
avalon.mix(Array.prototype, {
//定位操作,返回数组中第一个等于给定参数的元素的索引值。
indexOf: function(item, index) {
var n = this.length,
i = ~~index
if (i < 0)
i += n
for (; i < n; i++)
if (this[i] === item)
return i
return -1
},
//定位引操作,同上,不过是从后遍历。
lastIndexOf: function(item, index) {
var n = this.length,
i = index == null ? n - 1 : index
if (i < 0)
i = Math.max(0, n + i)
for (; i >= 0; i--)
if (this[i] === item)
return i
return -1
},
//迭代操作,将数组的元素挨个儿传入一个函数中执行。Ptototype.js的对应名字为each。
forEach: iterator('', '_', ''),
//迭代类 在数组中的每个项上运行一个函数,如果此函数的值为真,则此元素作为新数组的元素收集起来,并返回新数组
filter: iterator('r=[],j=0,', 'if(_)r[j++]=this[i]', 'return r'),
//收集操作,将数组的元素挨个儿传入一个函数中执行,然后把它们的返回值组成一个新数组返回。Ptototype.js的对应名字为collect。
map: iterator('r=[],', 'r[i]=_', 'return r'),
//只要数组中有一个元素满足条件(放进给定函数返回true),那么它就返回true。Ptototype.js的对应名字为any。
some: iterator('', 'if(_)return true', 'return false'),
//只有数组中的元素都满足条件(放进给定函数返回true),它才返回true。Ptototype.js的对应名字为all。
every: iterator('', 'if(!_)return false', 'return true')
})
}
if (!root.contains) { //safari5+是把contains方法放在Element.prototype上而不是Node.prototype
Node.prototype.contains = function(arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
/*********************************************************************
* Configure *
**********************************************************************/
function kernel(settings) {
for (var p in settings) {
if (!ohasOwn.call(settings, p))
continue
var val = settings[p]
if (typeof kernel.plugins[p] === "function") {
kernel.plugins[p](val)
} else {
kernel[p] = val
}
}
return this
}
var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
function escapeRegExp(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return (target + "").replace(rregexp, "\\$&")
}
var plugins = {
alias: function(val) {
var map = kernel.alias
for (var c in val) {
if (ohasOwn.call(val, c)) {
var prevValue = map[c]
var currValue = val[c]
if (prevValue) {
avalon.error("注意 " + c + " 已经重写过")
}
map[c] = currValue
}
}
},
loader: function(bool) {
if (bool) {
window.define = innerRequire.define
window.require = innerRequire
} else {
window.define = otherDefine
window.require = otherRequire
}
},
interpolate: function(array) {
if (Array.isArray(array) && array[0] && array[1] && array[0] !== array[1]) {
openTag = array[0]
closeTag = array[1]
var o = escapeRegExp(openTag),
c = escapeRegExp(closeTag)
rexpr = new RegExp(o + "(.*?)" + c)
rexprg = new RegExp(o + "(.*?)" + c, "g")
rbind = new RegExp(o + ".*?" + c + "|\\sms-")
}
}
}
kernel.plugins = plugins
kernel.plugins['interpolate'](["{{", "}}"])
kernel.alias = {}
avalon.config = kernel
/*********************************************************************
* 迷你jQuery对象的原型方法 *
**********************************************************************/
function hyphen(target) {
//转换为连字符线风格
return target.replace(/([a-z\d])([A-Z]+)/g, "$1-$2").toLowerCase()
}
function camelize(target) {
//转换为驼峰风格
if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
return target //提前判断,提高getStyle等的效率
}
return target.replace(/[-_][^-_]/g, function(match) {
return match.charAt(1).toUpperCase()
})
}
var rparse = /^(?:null|false|true|NaN|\{.*\}|\[.*\])$/
var rnospaces = /\S+/g
avalon.fn.mix({
hasClass: function(cls) {
var el = this[0] || {}
if (el.nodeType === 1) {
return !!el.className && (" " + el.className + " ").indexOf(" " + cls + " ") > -1
}
},
addClass: function(cls) {
var node = this[0]
if (cls && typeof cls === "string" && node && node.nodeType === 1) {
if (!node.className) {
node.className = cls
} else {
var a = (node.className + " " + cls).match(rnospaces)
a.sort()
for (var j = a.length - 1; j > 0; --j)
if (a[j] === a[j - 1])
a.splice(j, 1)
node.className = a.join(" ")
}
}
return this
},
removeClass: function(cls) {
var node = this[0]
if (cls && typeof cls > "o" && node && node.nodeType === 1 && node.className) {
var classNames = (cls || "").match(rnospaces) || []
var cl = classNames.length
var set = " " + node.className.match(rnospaces).join(" ") + " "
for (var c = 0; c < cl; c++) {
set = set.replace(" " + classNames[c] + " ", " ")
}
node.className = set.slice(1, set.length - 1)
}
return this
},
toggleClass: function(value, stateVal) {
var state = stateVal,
className, i = 0
var classNames = value.match(rnospaces) || []
var isBool = typeof stateVal === "boolean"
while ((className = classNames[i++])) {
state = isBool ? state : !this.hasClass(className)
this[state ? "addClass" : "removeClass"](className)
}
return this
},
attr: function(name, value) {
if (arguments.length === 2) {
this[0].setAttribute(name, value)
return this
} else {
return this[0].getAttribute(name)
}
},
data: function(name, value) {
name = "data-" + hyphen(name || "")
switch (arguments.length) {
case 2:
this.attr(name, value)
return this
case 1:
var val = this.attr(name)
return parseData(val)
case 0:
var attrs = this[0].attributes,
ret = {}
for (var i = 0, attr; attr = attrs[i++]; ) {
name = attr.name
if (!name.indexOf("data-")) {
name = camelize(name.slice(5))
ret[name] = parseData(attr.value)
}
}
return ret
}
},
removeData: function(name) {
name = "data-" + hyphen(name)
this[0].removeAttribute(name)
return this
},
css: function(name, value) {
return avalon.css(this, name, value)
},
position: function() {
var offsetParent, offset,
elem = this[0],
parentOffset = {
top: 0,
left: 0
};
if (!elem) {
return;
}
if (this.css("position") === "fixed") {
offset = elem.getBoundingClientRect()
} else {
offsetParent = this.offsetParent() //得到真正的offsetParent
offset = this.offset() // 得到正确的offsetParent
if (offsetParent[0].tagName !== "HTML") {
parentOffset = offsetParent.offset()
}
parentOffset.top += avalon.css(offsetParent[0], "borderTopWidth", true)
parentOffset.left += avalon.css(offsetParent[0], "borderLeftWidth", true)
}
return {
top: offset.top - parentOffset.top - avalon.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - avalon.css(elem, "marginLeft", true)
};
},
offsetParent: function() {
var offsetParent = this[0].offsetParent || root;
while (offsetParent && (offsetParent.tagName !== "HTML") && avalon.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent;
}
return avalon(offsetParent || root)
},
bind: function(type, fn, phase) {
if (this[0]) { //此方法不会链
return avalon.bind(this[0], type, fn, phase)
}
},
unbind: function(type, fn, phase) {
if (this[0]) {
avalon.unbind(this[0], type, fn, phase)
}
return this
},
val: function(value) {
var node = this[0]
if (node && node.nodeType === 1) {
var get = arguments.length === 0
var access = get ? ":get" : ":set"
var fn = valHooks[getValType(node) + access]
if (fn) {
var val = fn(node, value)
} else if (get) {
return (node.value || "").replace(/\r/g, "")
} else {
node.value = value
}
}
return get ? val : this
}
})
function parseData(val) {
var _eval = false
if (rparse.test(val) || +val + "" === val) {
_eval = true
}
try {
return _eval ? eval("0," + val) : val
} catch (e) {
return val
}
}
//生成avalon.fn.scrollLeft, avalon.fn.scrollTop方法
avalon.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(method, prop) {
avalon.fn[method] = function(val) {
var node = this[0] || {}, win = getWindow(node),
top = method === "scrollTop";
if (!arguments.length) {
return win ? (prop in win) ? win[prop] : root[method] : node[method];
} else {
if (win) {
win.scrollTo(!top ? val : avalon(win).scrollLeft(), top ? val : avalon(win).scrollTop())
} else {
node[method] = val;
}
}
}
})
function getWindow(node) {
return node.window && node.document ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false;
}
//=============================css相关=======================
var cssHooks = avalon.cssHooks = {}
var prefixes = ['', '-webkit-', '-o-', '-moz-', '-ms-']
var cssMap = {
"float": 'cssFloat' in root.style ? 'cssFloat' : 'styleFloat',
background: "backgroundColor"
}
avalon.cssNumber = oneObject("columnCount,order,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom")
avalon.cssName = function(name, host, camelCase) {
if (cssMap[name]) {
return cssMap[name]
}
host = host || root.style
for (var i = 0, n = prefixes.length; i < n; i++) {
camelCase = camelize(prefixes[i] + name)
if (camelCase in host) {
return (cssMap[name] = camelCase)
}
}
return null
}
cssHooks["@:set"] = function(node, name, value) {
try { //node.style.width = NaN;node.style.width = "xxxxxxx";node.style.width = undefine 在旧式IE下会抛异常
// Support: 在Chrome, Safari下用空字符串去掉 !important;
node.style[name] = "";
node.style[name] = value
} catch (e) {
}
}
if (window.getComputedStyle) {
cssHooks["@:get"] = function(node, name) {
var ret, styles = window.getComputedStyle(node, null)
if (styles) {
ret = name === "filter" ? styles.getPropertyValue(name) : styles[name]
if (ret === "") {
ret = node.style[name] //其他浏览器需要我们手动取内联样式
}
}
return ret
}
cssHooks["opacity:get"] = function(node) {
var ret = cssHooks["@:get"](node, "opacity")
return ret === "" ? "1" : ret
}
} else {
var rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i
var rposition = /^(top|right|bottom|left)$/
var ie8 = !!window.XDomainRequest
var salpha = "DXImageTransform.Microsoft.Alpha"
var border = {
thin: ie8 ? '1px' : '2px',
medium: ie8 ? '3px' : '4px',
thick: ie8 ? '5px' : '6px'
}
cssHooks["@:get"] = function(node, name) {
//取得精确值,不过它有可能是带em,pc,mm,pt,%等单位
var currentStyle = node.currentStyle
var ret = currentStyle[name]
if ((rnumnonpx.test(ret) && !rposition.test(ret))) {
//①,保存原有的style.left, runtimeStyle.left,
var style = node.style,
left = style.left,
rsLeft = node.runtimeStyle.left
//②由于③处的style.left = xxx会影响到currentStyle.left,
//因此把它currentStyle.left放到runtimeStyle.left,
//runtimeStyle.left拥有最高优先级,不会style.left影响
node.runtimeStyle.left = currentStyle.left
//③将精确值赋给到style.left,然后通过IE的另一个私有属性 style.pixelLeft
//得到单位为px的结果;fontSize的分支见http://bugs.jquery.com/ticket/760
style.left = name === 'fontSize' ? '1em' : (ret || 0)
ret = style.pixelLeft + "px"
//④还原 style.left,runtimeStyle.left
style.left = left
node.runtimeStyle.left = rsLeft
}
if (ret === "medium") {
name = name.replace("Width", "Style")
//border width 默认值为medium,即使其为0"
if (currentStyle[name] === "none") {
ret = "0px"
}
}
return ret === "" ? "auto" : border[ret] || ret
}
cssHooks["opacity:set"] = function(node, name, value) {
node.style.filter = 'alpha(opacity=' + value * 100 + ')'
node.style.zoom = 1
}
cssHooks["opacity:get"] = function(node) {
//这是最快的获取IE透明值的方式,不需要动用正则了!
var alpha = node.filters.alpha || node.filters[salpha],
op = alpha ? alpha.opacity : 100
return (op / 100) + "" //确保返回的是字符串
}
}
"top,left".replace(rword, function(name) {
cssHooks[name + ":get"] = function(node) {
var computed = cssHooks["@:get"](node, name)
return /px$/.test(computed) ? computed :
avalon(node).position()[name] + "px"
}
})
"Width,Height".replace(rword, function(name) {
var method = name.toLowerCase(),
clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name
avalon.fn[method] = function(value) {
var node = this[0]
if (arguments.length === 0) {
if (node.setTimeout) { //取得窗口尺寸,IE9后可以用node.innerWidth /innerHeight代替
return node["inner" + name] || node.document.documentElement[clientProp]
}
if (node.nodeType === 9) { //取得页面尺寸
var doc = node.documentElement
//FF chrome html.scrollHeight< body.scrollHeight
//IE 标准模式 : html.scrollHeight> body.scrollHeight
//IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp])
}
return parseFloat(this.css(method)) || 0
} else {
return this.css(method, value)
}
}
})
avalon.fn.offset = function() { //取得距离页面左右角的坐标
var node = this[0],
doc = node && node.ownerDocument
var pos = {
left: 0,
top: 0
}
if (!doc) {
return pos
}
//http://hkom.blog1.fc2.com/?mode=m&no=750 body的偏移量是不包含margin的
//我们可以通过getBoundingClientRect来获得元素相对于client的rect.
//http://msdn.microsoft.com/en-us/library/ms536433.aspx
var box = node.getBoundingClientRect(),
//chrome1+, firefox3+, ie4+, opera(yes) safari4+
win = doc.defaultView || doc.parentWindow,
root = (navigator.vendor || doc.compatMode === "BackCompat") ? doc.body : doc.documentElement,
clientTop = root.clientTop >> 0,
clientLeft = root.clientLeft >> 0,
scrollTop = win.pageYOffset || root.scrollTop,
scrollLeft = win.pageXOffset || root.scrollLeft
// 把滚动距离加到left,top中去。
// IE一些版本中会自动为HTML元素加上2px的border,我们需要去掉它
// http://msdn.microsoft.com/en-us/library/ms533564(VS.85).aspx
pos.top = box.top + scrollTop - clientTop
pos.left = box.left + scrollLeft - clientLeft
return pos
}
//=============================val相关=======================
function getValType(el) {
var ret = el.tagName.toLowerCase()
return ret === "input" && /checkbox|radio/.test(el.type) ? "checked" : ret
}
var valHooks = {
"option:get": function(node) {
// IE 9-10下如果option元素没有定义value而在设置innerText时没有把两边的空白去掉,那么
// 取el.text,浏览器会进行trim, 并且伪造一个value值,此值会在刚才trim的结果两边添加了一些空白
if (node.hasAttribute) {
return node.hasAttribute("value") ? node.value : node.text
}
var val = node.attributes.value //specified 在较新的浏览器总是返回true, 因此不可靠,需要用hasAttribute
return val === void 0 ? node.text : val.specified ? node.value : node.text
},
"select:get": function(node, value) {
var option, options = node.options,
index = node.selectedIndex,
getter = valHooks["option:get"],
one = node.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ? max : one ? index : 0
for (; i < max; i++) {
option = options[i]
//旧式IE在reset后不会改变selected,需要改用i === index判定
//我们过滤所有disabled的option元素,但在safari5下,如果设置select为disable,那么其所有孩子都disable
//因此当一个元素为disable,需要检测其是否显式设置了disable及其父节点的disable情况
if ((option.selected || i === index) && !option.disabled) {
value = getter(option)
if (one) {
return value
}
//收集所有selected值组成数组返回
values.push(value)
}
}
return values
},
"select:set": function(node, values) {
values = [].concat(values) //强制转换为数组
var getter = valHooks["option:get"]
for (var i = 0, el; el = node.options[i++]; ) {
el.selected = !!~values.indexOf(getter(el))
}
if (!values.length) {
node.selectedIndex = -1
}
}
}
/*********************************************************************
* Array Helper *
**********************************************************************/
avalon.Array = {
ensure: function(target) {
//只有当前数组不存在此元素时只添加它
var args = aslice.call(arguments, 1)
args.forEach(function(el) {
if (!~target.indexOf(el)) {
target.push(el)
}
})
return target
},
removeAt: function(target, index) {
//移除数组中指定位置的元素,返回布尔表示成功与否。
return !!target.splice(index, 1).length
},
remove: function(target, item) {
//移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否。
var index = target.indexOf(item)
if (~index)
return avalon.Array.removeAt(target, index)
return false
}
}
/************************************************************************
* parseHTML *
************************************************************************/
var rtagName = /<([\w:]+)/,
//取得其tagName
rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rcreate = W3C ? /[^\d\D]/ : /(<(?:script|link|style|meta|noscript))/ig,
scriptTypes = oneObject("text/javascript", "text/ecmascript", "application/ecmascript", "application/javascript", "text/vbscript"),
//需要处理套嵌关系的标签
rnest = /<(?:tb|td|tf|th|tr|col|opt|leg|cap|area)/
//parseHTML的辅助变量
var tagHooks = {
area: [1, "<map>"],
param: [1, "<object>"],
col: [2, "<table><tbody></tbody><colgroup>", "</table>"],
legend: [1, "<fieldset>"],
option: [1, "<select multiple='multiple'>"],
thead: [1, "<table>", "</table>"],
tr: [2, "<table><tbody>"],
td: [3, "<table><tbody><tr>"],
//IE6-8在用innerHTML生成节点时,不能直接创建no-scope元素与HTML5的新标签
_default: W3C ? [0, ""] : [1, "X<div>"] //div可以不用闭合
}
tagHooks.optgroup = tagHooks.option
tagHooks.tbody = tagHooks.tfoot = tagHooks.colgroup = tagHooks.caption = tagHooks.thead
tagHooks.th = tagHooks.td
avalon.clearChild = function(node) {
while (node.firstChild) {
node.removeChild(node.firstChild)
}
return node
}
avalon.parseHTML = function(html) {
html = html.replace(rxhtml, "<$1></$2>").trim()
var tag = (rtagName.exec(html) || ["", ""])[1].toLowerCase(),
//取得其标签名
wrap = tagHooks[tag] || tagHooks._default,
fragment = documentFragment.cloneNode(false),
wrapper = domParser,
firstChild