forked from RubyLouvre/avalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13 dom.js
544 lines (528 loc) · 19.8 KB
/
13 dom.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
/*********************************************************************
* avalon的原型方法定义区 *
**********************************************************************/
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 fakeClassListMethods = {
_toString: function() {
var node = this.node
var cls = node.className
var str = typeof cls === "string" ? cls : cls.baseVal
return str.split(/\s+/).join(" ")
},
_contains: function(cls) {
return (" " + this + " ").indexOf(" " + cls + " ") > -1
},
_add: function(cls) {
if (!this.contains(cls)) {
this._set(this + " " + cls)
}
},
_remove: function(cls) {
this._set((" " + this + " ").replace(" " + cls + " ", " "))
},
__set: function(cls) {
cls = cls.trim()
var node = this.node
if (rsvg.test(node)) {
//SVG元素的className是一个对象 SVGAnimatedString { baseVal="", animVal=""},只能通过set/getAttribute操作
node.setAttribute("class", cls)
} else {
node.className = cls
}
} //toggle存在版本差异,因此不使用它
}
function fakeClassList(node) {
if (!("classList" in node)) {
node.classList = {
node: node
}
for (var k in fakeClassListMethods) {
node.classList[k.slice(1)] = fakeClassListMethods[k]
}
}
return node.classList
}
"add,remove".replace(rword, function(method) {
avalon.fn[method + "Class"] = function(cls) {
var el = this[0]
//https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
if (cls && typeof cls === "string" && el && el.nodeType === 1) {
cls.replace(/\S+/g, function(c) {
fakeClassList(el)[method](c)
})
}
return this
}
})
avalon.fn.mix({
hasClass: function(cls) {
var el = this[0] || {}
return el.nodeType === 1 && fakeClassList(el).contains(cls)
},
toggleClass: function(value, stateVal) {
var className, i = 0
var classNames = value.split(/\s+/)
var isBool = typeof stateVal === "boolean"
while ((className = classNames[i++])) {
var state = isBool ? stateVal : !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 ret = {}
ap.forEach.call(this[0].attributes, function(attr) {
if (attr) {
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) {
if (avalon.isPlainObject(name)) {
for (var i in name) {
avalon.css(this, i, name[i])
}
} else {
var ret = avalon.css(this, name, value)
}
return ret !== void 0 ? ret : this
},
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
while (offsetParent && avalon.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent;
}
return avalon(offsetParent)
},
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(data) {
try {
if (typeof data === "object")
return data
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null : +data + "" === data ? +data : rbrace.test(data) ? avalon.parseJSON(data) : data
} catch (e) {
}
return data
}
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g
avalon.parseJSON = window.JSON ? JSON.parse : function(data) {
if (typeof data === "string") {
data = data.trim();
if (data) {
if (rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
return (new Function("return " + data))();
}
}
avalon.error("Invalid JSON: " + data);
}
return data
}
//生成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": W3C ? "cssFloat" : "styleFloat"
}
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下会抛异常
node.style[name] = value
} catch (e) {
}
}
if (window.getComputedStyle) {
cssHooks["@:get"] = function(node, name) {
if (!node || !node.style) {
throw new Error("getComputedStyle要求传入一个节点 " + node)
}
var ret, styles = 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 ralpha = /alpha\([^)]*\)/i
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) {
var style = node.style
var opacity = isFinite(value) && value <= 1 ? "alpha(opacity=" + value * 100 + ")" : ""
var filter = style.filter || "";
style.zoom = 1
//不能使用以下方式设置透明度
//node.filters.alpha.opacity = value * 100
style.filter = (ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
filter + " " + opacity).trim()
if (!style.filter) {
style.removeAttribute("filter")
}
}
cssHooks["opacity:get"] = function(node) {
//这是最快的获取IE透明值的方式,不需要动用正则了!
var alpha = node.filters.alpha || node.filters[salpha],
op = alpha && alpha.enabled ? 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"
}
})
var cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}
var rdisplayswap = /^(none|table(?!-c[ea]).+)/
function showHidden(node, array) {
//http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
if (node.offsetWidth <= 0) { //opera.offsetWidth可能小于0
if (rdisplayswap.test(cssHooks["@:get"](node, "display"))) {
var obj = {
node: node
}
for (var name in cssShow) {
obj[name] = node.style[name]
node.style[name] = cssShow[name]
}
array.push(obj)
}
var parent = node.parentNode
if (parent && parent.nodeType === 1) {
showHidden(parent, array)
}
}
}
"Width,Height".replace(rword, function(name) { //fix 481
var method = name.toLowerCase(),
clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name
cssHooks[method + ":get"] = function(node, which, override) {
var boxSizing = -4
if (typeof override === "number") {
boxSizing = override
}
which = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"]
var ret = node[offsetProp] // border-box 0
if (boxSizing === 2) { // margin-box 2
return ret + avalon.css(node, "margin" + which[0], true) + avalon.css(node, "margin" + which[1], true)
}
if (boxSizing < 0) { // padding-box -2
ret = ret - avalon.css(node, "border" + which[0] + "Width", true) - avalon.css(node, "border" + which[1] + "Width", true)
}
if (boxSizing === -4) { // content-box -4
ret = ret - avalon.css(node, "padding" + which[0], true) - avalon.css(node, "padding" + which[1], true)
}
return ret
}
cssHooks[method + "&get"] = function(node) {
var hidden = [];
showHidden(node, hidden);
var val = cssHooks[method + ":get"](node)
for (var i = 0, obj; obj = hidden[i++]; ) {
node = obj.node
for (var n in obj) {
if (typeof obj[n] === "string") {
node.style[n] = obj[n]
}
}
}
return val;
}
avalon.fn[method] = function(value) { //会忽视其display
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 cssHooks[method + "&get"](node)
} else {
return this.css(method, value)
}
}
avalon.fn["inner" + name] = function() {
return cssHooks[method + ":get"](this[0], void 0, -2)
}
avalon.fn["outer" + name] = function(includeMargin) {
return cssHooks[method + ":get"](this[0], void 0, includeMargin === true ? 2 : 0)
}
})
avalon.fn.offset = function() { //取得距离页面左右角的坐标
var node = this[0],
box = {
left: 0,
top: 0
}
if (!node || !node.tagName || !node.ownerDocument) {
return box
}
var doc = node.ownerDocument,
body = doc.body,
root = doc.documentElement,
win = doc.defaultView || doc.parentWindow
if (!avalon.contains(root, node)) {
return box
}
//http://hkom.blog1.fc2.com/?mode=m&no=750 body的偏移量是不包含margin的
//我们可以通过getBoundingClientRect来获得元素相对于client的rect.
//http://msdn.microsoft.com/en-us/library/ms536433.aspx
if (node.getBoundingClientRect) {
box = node.getBoundingClientRect() // BlackBerry 5, iOS 3 (original iPhone)
}
//chrome/IE6: body.scrollTop, firefox/other: root.scrollTop
var clientTop = root.clientTop || body.clientTop,
clientLeft = root.clientLeft || body.clientLeft,
scrollTop = Math.max(win.pageYOffset || 0, root.scrollTop, body.scrollTop),
scrollLeft = Math.max(win.pageXOffset || 0, root.scrollLeft, body.scrollLeft)
// 把滚动距离加到left,top中去。
// IE一些版本中会自动为HTML元素加上2px的border,我们需要去掉它
// http://msdn.microsoft.com/en-us/library/ms533564(VS.85).aspx
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
}
}
//==================================val相关============================
function getValType(el) {
var ret = el.tagName.toLowerCase()
return ret === "input" && /checkbox|radio/.test(el.type) ? "checked" : ret
}
var roption = /^<option(?:\s+\w+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*\s+value[\s=]/i
var valHooks = {
"option:get": IEVersion ? function(node) {
//在IE11及W3C,如果没有指定value,那么node.value默认为node.text(存在trim作),但IE9-10则是取innerHTML(没trim操作)
//specified并不可靠,因此通过分析outerHTML判定用户有没有显示定义value
return roption.test(node.outerHTML) ? node.value : node.text.trim()
} : function(node) {
return node.value
},
"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, optionSet) {
values = [].concat(values) //强制转换为数组
var getter = valHooks["option:get"]
for (var i = 0, el; el = node.options[i++]; ) {
if ((el.selected = values.indexOf(getter(el)) > -1)) {
optionSet = true
}
}
if (!optionSet) {
node.selectedIndex = -1
}
}
}