-
Notifications
You must be signed in to change notification settings - Fork 0
/
zepto.js
2008 lines (1819 loc) · 95 KB
/
zepto.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
/* Zepto v1.2.0 - zepto event ajax form ie - zeptojs.com/license */
(function (global, factory) {
//amd模块
if (typeof define === 'function' && define.amd)
define(function () {
return factory(global)
})
else
factory(global)
}(this, function (window) {
var Zepto = (function () {
var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter,
slice = emptyArray.slice,
document = window.document,
elementDisplay = {}, classCache = {},
cssNumber = {
'column-count': 1,
'columns': 1,
'font-weight': 1,
'line-height': 1,
'opacity': 1,
'z-index': 1,
'zoom': 1
},
fragmentRE = /^\s*<(\w+|!)[^>]*>/,//匹配html标签,包括注释在内
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,//?:不捕获分组,此处匹配简单空标签
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//匹配除了area|br|col|embed|hr|img|input|link|meta|param之外其他标签,类似这个形式<div/>
rootNodeRE = /^(?:body|html)$/i,//匹配html和body
capitalRE = /([A-Z])/g,//匹配大写字母
// special attributes that should be get/set via method calls
//需要通过get/set方法获取的特殊属性,意思是要操作这些属性,需要调用val(),css(),html()等等这些方法,不能直接通过修改属性
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
adjacencyOperators = ['after', 'prepend', 'before', 'append'],
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
'tr': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},//自定义的一些container元素
readyRE = /complete|loaded|interactive/,
simpleSelectorRE = /^[\w-]*$/,//匹配包括下划线和‘-’的任何单词字符,识别html标签
class2type = {},
toString = class2type.toString,
zepto = {},
camelize, uniq,
tempParent = document.createElement('div'),
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},//此处应是转换js的保留字
//是否为数组对象
isArray = Array.isArray ||
function (object) {
return object instanceof Array
}
//判断给定元素是否和给定的css表达式契合
zepto.matches = function (element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
/*新api matches或matchesSelector*/
var matchesSelector = element.matches || element.webkitMatchesSelector ||
element.mozMatchesSelector || element.oMatchesSelector ||
element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
// 兼容方案
var match, parent = element.parentNode, temp = !parent
//不存在父节点,动态创建div作为父节点
if (temp) (parent = tempParent).appendChild(element)
match = ~zepto.qsa(parent, selector).indexOf(element)//~为按位取反,找不到对应值时-1被转化为0,其他转化为非0值,if判断时0 为假,非0 均为真,妈的智障
temp && tempParent.removeChild(element)//恢复临时变量
return match
}
//调用Object的toString方法获取当前obj类型
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}
//是否为函数
function isFunction(value) {
return type(value) == "function"
}
//当前对象是否为window
function isWindow(obj) {
return obj != null && obj == obj.window
}
//是否为document节点
function isDocument(obj) {
return obj != null && obj.nodeType == obj.DOCUMENT_NODE
}
//是否为object
function isObject(obj) {
return type(obj) == "object"
}
//是否为原始Object对象
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
//是否类数组类型
function likeArray(obj) {
var length = !!obj && 'length' in obj && obj.length,
type = $.type(obj)
//排除函数对象,全局属性自动添加到window,估需要排除window
return 'function' != type && !isWindow(obj) && (
'array' == type || length === 0 ||
(typeof length == 'number' && length > 0 && (length - 1) in obj)//看起来像鸭子,他就是鸭子
)
}
//去除数组null值,保留非空值
function compact(array) {
return filter.call(array, function (item) {
return item != null
})
}
//数组降维(可以)
function flatten(array) {
return array.length > 0 ? $.fn.concat.apply([], array) : array
}
//字符串驼峰化
camelize = function (str) {
return str.replace(/-+(.)?/g, function (match, chr) {
return chr ? chr.toUpperCase() : ''//.匹配除“\n”和"\r"之外的任何单个字符,将-后面的第一个字符变成大写
})
}
//命名从驼峰转化为-隔开
function dasherize(str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase()
}
//去重。。。(工具)
uniq = function (array) {
return filter.call(array, function (item, idx) {
return array.indexOf(item) == idx
})
}
//返回一个正则表达式,用来判断当前指定的name是否存在node的class中
function classRE(name) {
return name in classCache ?//使用过的话则缓存起来,下次再用
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))//此处前后空格的意义在于,class存在多个值时,中间是以空格隔开
}
//除去cssNumber中规定的css字段外,统一加上px后缀
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}
//获取节点的当前的display属性
function defaultDisplay(nodeName) {
var element, display
//首先检查是否有缓存,没有缓存时利用新创建的节点来获取display属性
if (!elementDisplay[nodeName]) {
element = document.createElement(nodeName)
document.body.appendChild(element)
display = getComputedStyle(element, '').getPropertyValue("display")
element.parentNode.removeChild(element)
display == "none" && (display = "block")//当display属性是隐藏时,修改为block
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]//命中缓存则直接返回
}
//兼容写法,获取子节点
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function (node) {
if (node.nodeType == 1) return node//兼容写法,仅获取Element元素
})
}
//Z对象构造函数
function Z(dom, selector) {
var i, len = dom ? dom.length : 0
for (i = 0; i < len; i++) this[i] = dom[i]
this.length = len
this.selector = selector || ''
}
// `$.zepto.fragment` takes a html string and an optional tag name
// to generate DOM nodes from the given html string.
// The generated DOM nodes are returned as an array.
// This function can be overridden in plugins for example to make
// it compatible with browsers that don't support the DOM fully.
//通过传入的html字符串构建节点,可以指定额外的属性
zepto.fragment = function (html, name, properties) {
var dom, nodes, container
// A special case optimization for a single tag
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))//创建简单标签
if (!dom) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")//类似<div/>转化成<div></div>
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1//不传入name则取当前tag的名称作为name
if (!(name in containers)) name = '*'//除了所定义之外的传入*,当做div处理
//选择合适的标签包裹起来
container = containers[name]
container.innerHTML = '' + html
//返回一个新的数组,并清空container里面的内容,借助这个函数将html字符串转化为node列表
dom = $.each(slice.call(container.childNodes), function () {
container.removeChild(this)
})
}
//此处是对传入的属性列表添加到构建的node列表上
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function (key, value) {
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
// `$.zepto.Z` swaps out the prototype of the given `dom` array
// of nodes with `$.fn` and thus supplying all the Zepto functions
// to the array. This method can be overridden in plugins.
//zepto.Z继承自$.fn,Z构造函数复制了节点列表的所有节点,从而使节点列表具有$.fn的所有功能
zepto.Z = function (dom, selector) {
return new Z(dom, selector)
}
// `$.zepto.isZ` should return `true` if the given object is a Zepto
// collection. This method can be overridden in plugins.
//是否Z对象
zepto.isZ = function (object) {
return object instanceof zepto.Z
}
// `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
// takes a CSS selector and an optional context (and handles various
// special cases).
// This method can be overridden in plugins.
zepto.init = function (selector, context) {
var dom
// If nothing given, return an empty Zepto collection
//选择器为空则返回空的Z对象
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()//去空格
// If it's a html fragment, create nodes from it
// Note: In both Chrome 21 and Firefox 15, DOM error 12
// is thrown if the fragment doesn't begin with <
//检测出如果是用字符串直接构建dom
if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
//如果提供context,则对context的每一个子元素进行selector匹配,返回一个列表
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
//css选择器,以document为根进行查找
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
//$(function(){})能执行的原因,在ready时会调用
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
//如果传入的已经是zeptop对象,则直接返回
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
//传入的是一个数组,则先去除null
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
//dom节点,构建成数组
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
//此处要通过字符串匹配,上面在string判断中已经出现过,理论上应该不可能再次命中,以下部分存疑
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
//最终结果实例化成一个zepto对象
return zepto.Z(dom, selector)
}
// `$` will be the base `Zepto` object. When calling this
// function just call `$.zepto.init, which makes the implementation
// details of selecting nodes and creating Zepto collections
// patchable in plugins.
//$(什么鬼)直接调用init方法
$ = function (selector, context) {
return zepto.init(selector, context)
}
//target继承source的方法和属性
function extend(target, source, deep) {
for (key in source)
//深复制,递归
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
// Copy all but undefined properties from one or more
// objects to the `target` object.
//继承操作,支持多重继承
$.extend = function (target) {
var deep, args = slice.call(arguments, 1)
//第一个参数为bool类型时,表示是否深克隆
if (typeof target == 'boolean') {
deep = target
target = args.shift()//第二个参数作为target
}
//遍历所有其他参数,逐个继承
args.forEach(function (arg) {
extend(target, arg, deep)
})
return target
}
// `$.zepto.qsa` is Zepto's CSS selector implementation which
// uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
// This method can be overridden in plugins.
//兼容版css选择器,使用querySelectorAll,获取所选节点下符合的所有元素
zepto.qsa = function (element, selector) {
var found,
maybeID = selector[0] == '#',//识别#id
maybeClass = !maybeID && selector[0] == '.',//识别.className
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // 获取筛选体,同时确保仅有一个字符的选择器能得到保留,例如a
isSimple = simpleSelectorRE.test(nameOnly)//识别html标签
return (element.getElementById && isSimple && maybeID) ? // Safari旧机型对getElementById不兼容
((found = element.getElementById(nameOnly)) ? [found] : []) :
(element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] ://非可选择节点
slice.call(//转化为数组
isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
maybeClass ? element.getElementsByClassName(nameOnly) : // 为.classname,使用getElementsByClassName获取
element.getElementsByTagName(selector) : // 单纯的tag
element.querySelectorAll(selector) // 组合表达式,返回取得的所有元素
)
}
//简单封装
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
}
//dom节点是否包含
$.contains = document.documentElement.contains ?
function (parent, node) {
return parent !== node && parent.contains(node)
} :
function (parent, node) {
while (node && (node = node.parentNode))
if (node === parent) return true
return false
}
//关键方法,arg如果为函数,则绑定执行环境之后返回执行结果,否则返回arg
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
//依旧简单封装,设置或删除属性
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
}
// access className property while respecting SVGAnimatedString
//获取或设置className属性,兼容svg,svg并不了解,此处略过
function className(node, value) {
var klass = node.className || '',
svg = klass && klass.baseVal !== undefined
if (value === undefined) return svg ? klass.baseVal : klass
svg ? (klass.baseVal = value) : (node.className = value)
}
// "true" => true
// "false" => false
// "null" => null
// "42" => 42
// "42.5" => 42.5
// "08" => "08"
// JSON => parse if valid
// String => self
//简单的反序列化
function deserializeValue(value) {
try {
return value ?
value == "true" ||
(value == "false" ? false :
value == "null" ? null :
+value + "" == value ? +value :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value)
: value
} catch (e) {
return value
}
}
$.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject
//是否空对象
$.isEmptyObject = function (obj) {
var name
for (name in obj) return false
return true
}
//判断是否是数字
$.isNumeric = function (val) {
var num = Number(val), type = typeof val
return val != null && type != 'boolean' &&
(type != 'string' || val.length) &&
!isNaN(num) && isFinite(num) || false
}
//检测数组中是否存在值
$.inArray = function (elem, array, i) {
return emptyArray.indexOf.call(array, elem, i)
}
$.camelCase = camelize
$.trim = function (str) {
return str == null ? "" : String.prototype.trim.call(str)
}
// plugin compatibility
$.uuid = 0
$.support = {}
$.expr = {}
$.noop = function () {
}
//map,遍历elements并对每一个项执行回调
$.map = function (elements, callback) {
var value, values = [], i, key
if (likeArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i)
if (value != null) values.push(value)//返回所有callback执行后的结果
}
else
for (key in elements) {
value = callback(elements[key], key)
if (value != null) values.push(value)//返回所有callback执行后的结果
}
return flatten(values)
}
//遍历数组或对象,对内容执行方法,直到callback返回false为止,返回原数组或对象
$.each = function (elements, callback) {
var i, key
if (likeArray(elements)) {
for (i = 0; i < elements.length; i++)
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
if (callback.call(elements[key], key, elements[key]) === false) return elements
}
return elements
}
//filter简单封装
$.grep = function (elements, callback) {
return filter.call(elements, callback)
}
if (window.JSON) $.parseJSON = JSON.parse
// Populate the class2type map
//初始化对象类型字典
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
// Define methods that will be available on all
// Zepto collections
$.fn = {
constructor: zepto.Z,
length: 0,
// Because a collection acts like an array
// copy over these useful array functions.
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
splice: emptyArray.splice,
indexOf: emptyArray.indexOf,
//将传入的所有数组合并成一个数组,同时支持Z实例
concat: function () {
var i, value, args = []
//这一步主要是起到转化作用
for (i = 0; i < arguments.length; i++) {
value = arguments[i]
args[i] = zepto.isZ(value) ? value.toArray() : value//当前如果是Z的实例,则将Z中的节点转化成数组
}
//此处起到数组降维的作用
return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)//将获得的所有数组拼接成一个数组,args如果是多维,将会降一级拼接
},
// `map` and `slice` in the jQuery API work differently
// from their array counterparts
//此处应是为了兼容jquery api,将参数位置调转
//封装后返回zepto对象
map: function (fn) {
return $($.map(this, function (el, i) {
return fn.call(el, i, el)
}))
},
slice: function () {
return $(slice.apply(this, arguments))
},
//$.ready
ready: function (callback) {
// need to check if document.body exists for IE as that browser reports
// document ready when it hasn't yet created the body element
if (readyRE.test(document.readyState) && document.body) callback($)//已加载完毕则立刻执行回调
else document.addEventListener('DOMContentLoaded', function () {//监听加载完毕事件
callback($)
}, false)
return this
},
//idx为空:将当前对象转化为数组返回,idx大于等于0时返回第idx个,小于0返回倒数第idx值
get: function (idx) {
return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
},
//类数组转化为数组
toArray: function () {
return this.get()
},
size: function () {
return this.length
},
//将当前集合中的元素从父节点中移除
remove: function () {
return this.each(function () {
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
//遍历操作,直到回调函数返回false
each: function (callback) {
emptyArray.every.call(this, function (el, idx) {
return callback.call(el, idx, el) !== false
})
return this
},
//筛选出所有符合的节点
filter: function (selector) {
if (isFunction(selector)) return this.not(this.not(selector))//负负得正。。。
//调用原生的fileter方法,选出匹配的节点列表
return $(filter.call(this, function (element) {
return zepto.matches(element, selector)
}))
},
//数组合并后去重
add: function (selector, context) {
return $(uniq(this.concat($(selector, context))))
},
is: function (selector) {
return this.length > 0 && zepto.matches(this[0], selector)
},
//找出所有不符合selector的项
not: function (selector) {
var nodes = []
//如果是函数,则对每个子节点执行函数并取出返回false的节点列表
if (isFunction(selector) && selector.call !== undefined)
this.each(function (idx) {
if (!selector.call(this, idx)) nodes.push(this)
})
else {
var excludes = typeof selector == 'string' ? this.filter(selector) ://字符串,正则匹配获取符合项
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) ://dom node列表,类数组
$(selector)//数组
this.forEach(function (el) {
if (excludes.indexOf(el) < 0) nodes.push(el)//筛选出所有不符合的节点
})
}
return $(nodes)
},
//slector为对象时,判断当前对象是否包含selector,为选择器时,返回符合选择器的节点
has: function (selector) {
return this.filter(function () {
return isObject(selector) ?
$.contains(this, selector) :
$(this).find(selector).size()
})
},
//获取当前对象指定index位置的元素,负数则从后往前数
eq: function (idx) {
return idx === -1 ? this.slice(idx) : this.slice(idx, +idx + 1)
},
//获取第一个子元素
first: function () {
var el = this[0]
return el && !isObject(el) ? el : $(el)//包装成zepto对象
},
//最后一个元素
last: function () {
var el = this[this.length - 1]
return el && !isObject(el) ? el : $(el)
},
//与filter的区别在于,find是对所有后代元素的子元素中进行筛选
find: function (selector) {
var result, $this = this
if (!selector) result = $()
else if (typeof selector == 'object')
//当slector是object时,如果当前对象子元素包含了selector的项,这个项才会返回
result = $(selector).filter(function () {
var node = this//此处this已经被绑定为特定的item
return emptyArray.some.call($this, function (parent) {
return $.contains(parent, node)
})
})
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
else result = this.map(function () {
return zepto.qsa(this, selector)
})
return result
},
//逐级往上,获取最上面一个匹配的父级节点
closest: function (selector, context) {
var nodes = [], collection = typeof selector == 'object' && $(selector)
this.each(function (_, node) {
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))//collection为对象时,判断当前节点是否在对象中,,不为对象时,则判断当前node和selector表达式是否契合
node = node !== context && !isDocument(node) && node.parentNode//逐级往上走,document节点除外
if (node && nodes.indexOf(node) < 0) nodes.push(node)
})
return $(nodes)
},
//与closest相似,但parents值匹配所有符合要求的父级元素
parents: function (selector) {
var ancestors = [], nodes = this
while (nodes.length > 0)
nodes = $.map(nodes, function (node) {
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
})
return filtered(ancestors, selector)
},
//返回符合要求的直接父级节点
parent: function (selector) {
return filtered(uniq(this.pluck('parentNode')), selector)
},
//获取所有元素的子节点,并用selector进行筛选
children: function (selector) {
return filtered(this.map(function () {
return children(this)
}), selector)
},
//返回每个元素的内容
contents: function () {
return this.map(function () {
return this.contentDocument || slice.call(this.childNodes)//frame节点时返回对应文档,其他的返回子节点
})
},
//获取符合条件的兄弟节点
siblings: function (selector) {
return filtered(this.map(function (i, el) {
return filter.call(children(el.parentNode), function (child) {
return child !== el
})
}), selector)
},
//清空所有子元素
empty: function () {
return this.each(function () {
this.innerHTML = ''
})
},
// `pluck` is borrowed from Prototype.js
//遍历元素列表,获取某个特定的属性的值拼成一个数组返回
pluck: function (property) {
return $.map(this, function (el) {
return el[property]
})
},
//显示所有元素
show: function () {
return this.each(function () {
this.style.display == "none" && (this.style.display = '')
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
this.style.display = defaultDisplay(this.nodeName)
})
},
//替换当前节点
replaceWith: function (newContent) {
return this.before(newContent).remove()//在当前节点插入新节点,随后删除当前节点
},
// 在每个匹配的元素外层包上一个html元素。structure参数可以是一个单独的元素或者一些嵌套的元素。也可以是一个html字符串片段或者dom节点。还可以是一个生成用来包元素的回调函数,这个函数返回前两种类型的包裹片段。
wrap: function (structure) {
var func = isFunction(structure)
if (this[0] && !func)
var dom = $(structure).get(0),//获取当前元素的第一个子节点,支持多种形式的元素如dom节点,html字符串原因在于此处用了$构造函数初始化
clone = dom.parentNode || this.length > 1//存在父节点,则dom存在于当前dom文档中,需要复制节点,防止改变原有dom结构
//对所有子节点调用wrapAll
return this.each(function (index) {
$(this).wrapAll(
func ? structure.call(this, index) ://支持返回包裹元素的函数形式
clone ? dom.cloneNode(true) : dom
)
})
},
//在当前元素外面包裹元素
wrapAll: function (structure) {
if (this[0]) {
//插入到同级节点
$(this[0]).before(structure = $(structure))
var children
// drill down to the inmost element
//一直往下走,直到没有子节点位置
while ((children = structure.children()).length) structure = children.first();
//将当前节点包裹进去
$(structure).append(this)
}
return this
},
//将当前每一个子节点的内容包裹在structure中,structure支持节点,函数
wrapInner: function (structure) {
var func = isFunction(structure)
return this.each(function (index) {
var self = $(this), contents = self.contents(),
dom = func ? structure.call(this, index) : structure//兼容函数和节点
contents.length ? contents.wrapAll(dom) : self.append(dom)//仅有一个子节点时直接用append
})
},
//解套,去除当前元素的第一层包裹
unwrap: function () {
this.parent().each(function () {
$(this).replaceWith($(this).children())
})
return this
},
//深度克隆当前元素,并返回克隆的子节点列表
clone: function () {
return this.map(function () {
return this.cloneNode(true)
})
},
//隐藏当前元素
hide: function () {
return this.css("display", "none")
},
//切换显示或隐藏,setting为true显示,false隐藏
toggle: function (setting) {
return this.each(function () {
var el = $(this);
//setting不显式传入时,根据当前的display属性,按相反切换
(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
},
//获取当前对象的所有节点的上一个兄弟节点,支持筛选器
prev: function (selector) {
return $(this.pluck('previousElementSibling')).filter(selector || '*')
},
//获取当前对象的所有节点的下一个兄弟节点,支持筛选器
next: function (selector) {
return $(this.pluck('nextElementSibling')).filter(selector || '*')
},
//获取或修改当前内容
html: function (html) {
return 0 in arguments ?//相当于arguments.length>=1
this.each(function (idx) {
var originHtml = this.innerHTML
$(this).empty().append(funcArg(this, html, idx, originHtml))//清空当前节点的内容,放入新的内容,支持函数,会传入新的html和旧的html内容
}) :
(0 in this ? this[0].innerHTML : null)//无参数时返回当前内容
},
//设置当前所有元素的文本
text: function (text) {
return 0 in arguments ?
this.each(function (idx) {
var newText = funcArg(this, text, idx, this.textContent)
this.textContent = newText == null ? '' : '' + newText//利用textContent设置节点文本
}) :
(0 in this ? this.pluck('textContent').join("") : null)
},
//获取或设置属性
attr: function (name, value) {
var result
return (typeof name == 'string' && !(1 in arguments)) ?
(0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) ://传入一个参数,获取属性值
this.each(function (idx) {
if (this.nodeType !== 1) return//非element,直接返回,没有获取attribute的必要
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])//对于object或array,直接配置键值对作为attribute
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))//对于字符串的以value为值进行配置
})
},
//移除属性,支持多个属性名用空格隔开的字符串
removeAttr: function (name) {
return this.each(function () {
this.nodeType === 1 && name.split(' ').forEach(function (attribute) {
setAttribute(this, attribute)//不传入属性值,即为移除
}, this)
})
},
//读取或设置dom属性
prop: function (name, value) {
name = propMap[name] || name//转换class等保留字
return (1 in arguments) ?//参数值多于一个,遍历所有元素设置属性值
this.each(function (idx) {
this[name] = funcArg(this, value, idx, this[name])
}) :
(this[0] && this[0][name])//返回属性值
},
//移除属性值
removeProp: function (name) {
name = propMap[name] || name//转换class等保留字
return this.each(function () {
delete this[name]//直接移除
})
},
//读取或写入dom的 data-* 属性,html5 data规范
data: function (name, value) {
var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()//转化为data-xxx形式,html5的data
var data = (1 in arguments) ?
this.attr(attrName, value) ://设置属性
this.attr(attrName)//返回属性
return data !== null ? deserializeValue(data) : undefined//返回属性值时将属性值反序列化之后返回
},
//获取或设置value属性,支持传入函数,不传入值时返回第一个元素的value
val: function (value) {
if (0 in arguments) {
if (value == null) value = ""
//设置所有元素的value
return this.each(function (idx) {
this.value = funcArg(this, value, idx, this.value)
})
} else {
return this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function () {
return this.selected
}).pluck('value') ://这里是对多选select元素进行操作,遍历所有子节点获取选中项
this[0].value)
}
},
//传入参数时,设置对于document的偏移,包括top,left,不传参数时,返回自身长宽已经相对于document的left和top
offset: function (coordinates) {
if (coordinates) return this.each(function (index) {
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),//获取配置参数
parentOffset = $this.offsetParent().offset(),//父节点偏移量
props = {
top: coords.top - parentOffset.top,//相对于document偏移量=父节点偏移量+节点对于父节点的偏移量(fixed,absolute)或节点对于自身的偏移量(relative)
left: coords.left - parentOffset.left
}
if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (!this.length) return null//不存在元素,直接返回
if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0]))//html元素外的元素
return {top: 0, left: 0}
var obj = this[0].getBoundingClientRect()//这个方法返回一个矩形对象,包含四个属性:left、top、right和bottom。分别表示元素各边与页面上边和左边的距离
return {
left: obj.left + window.pageXOffset,//加上滚动距离,即为距离根节点的距离
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),//舍入为最接近的整数
height: Math.round(obj.height)
}
},
//操作css属性的方法,value不传值时返回当前属性,传入时为修改,property支持字符串和数组
css: function (property, value) {
if (arguments.length < 2) {
var element = this[0]
if (typeof property == 'string') {//获取单个css属性
if (!element) return
return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property)//获取当前节点特定的css样式
} else if (isArray(property)) {//获取属性列表
if (!element) return
var props = {}
var computedStyle = getComputedStyle(element, '')
$.each(property, function (_, prop) {
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props//返回集合
}
}
var css = ''
if (type(property) == 'string') {
if (!value && value !== 0)//此处应是如null,意为移除当前css,'',显式传入undefined时
this.each(function () {
this.style.removeProperty(dasherize(property))//移除css属性
})
else
css = dasherize(property) + ":" + maybeAddPx(property, value)//拼凑css字符串
} else {
//property传入数组
for (key in property)
if (!property[key] && property[key] !== 0)//同上,移除整个列表的css属性
this.each(function () {
this.style.removeProperty(dasherize(key))
})
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
}
return this.each(function () {
this.style.cssText += ';' + css//直接将属性写入style中
})
},
//传入参数时返回传入节点在当前元素列表中的位置,否则返回当前第一个元素在父节点中的位置
index: function (element) {
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
//判断当前实例的集合中是否存在指定name的class
hasClass: function (name) {
if (!name) return false
return emptyArray.some.call(this, function (el) {
return this.test(className(el))
}, classRE(name))
},
//添加class
addClass: function (name) {
if (!name) return this
return this.each(function (idx) {
if (!('className' in this)) return//不支持className直接返回
classList = []
//先获取当前class
var cls = className(this), newName = funcArg(this, name, idx, cls)
//支持用空格隔开的字符串
newName.split(/\s+/g).forEach(function (klass) {
if (!$(this).hasClass(klass)) classList.push(klass)//仅添加新class
}, this)
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))//合并最终classs并添加
})
},
//移除classname
removeClass: function (name) {
return this.each(function (idx) {
if (!('className' in this)) return
if (name === undefined) return className(this, '')//清空所有的class
classList = className(this)
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function (klass) {
classList = classList.replace(classRE(klass), " ")//移除匹配的属性
})
className(this, classList.trim())//重新设置classname
})
},
//当前class有则移除,无则添加
toggleClass: function (name, when) {
if (!name) return this
return this.each(function (idx) {