源码

  1. // Zepto.js
  2. // (c) 2010-2015 Thomas Fuchs
  3. // Zepto.js may be freely distributed under the MIT license.
  4.  
  5. var Zepto = (function() {
  6. //定义局部变量 concat = emptyArray.concat 缩短作用域链
  7. var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,
  8.  
  9. document = window.document,
  10.  
  11. //缓存元素的默认display属性
  12. elementDisplay = {},
  13.  
  14. //缓存匹配class正则表达式 ,hasClass判断用到,
  15. classCache = {},
  16.  
  17. //设置CSS时,不用加px单位的属性
  18. cssNumber = { 'column-count': , 'columns': , 'font-weight': , 'line-height': ,'opacity': , 'z-index': , 'zoom': },
  19. //匹配HTML代码
  20. fragmentRE = /^\s*<(\w+|!)[^>]*>/,
  21. //TODO 匹配单个HTML标签
  22. singleTagRE = /^<(\w+)\s*\/?>(?:<\/\>|)$/,
  23. //TODO 匹配自闭合标签
  24. tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
  25. //匹配根节点
  26. rootNodeRE = /^(?:body|html)$/i,
  27. //匹配A-Z
  28. capitalRE = /([A-Z])/g,
  29.  
  30. // special attributes that should be get/set via method calls
  31. //需要提供get和set的方法名
  32. methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
  33. //相邻DOM的操作
  34. adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
  35. table = document.createElement('table'),
  36. tableRow = document.createElement('tr'),
  37.  
  38. //这里的用途是当需要给tr,tbody,thead,tfoot,td,th设置innerHTMl的时候,需要用其父元素作为容器来装载HTML字符串
  39. containers = {
  40. 'tr': document.createElement('tbody'),
  41. 'tbody': table, 'thead': table, 'tfoot': table,
  42. 'td': tableRow, 'th': tableRow,
  43. '*': document.createElement('div')
  44. },
  45. //当DOM ready的时候,document会有以下三种状态的一种
  46. readyRE = /complete|loaded|interactive/,
  47. simpleSelectorRE = /^[\w-]*$/,
  48. //缓存对象类型,用于类型判断 如object
  49. class2type = {},
  50. toString = class2type.toString,
  51. zepto = {},
  52. camelize, uniq,
  53. tempParent = document.createElement('div'),
  54. propMap = {
  55. 'tabindex': 'tabIndex',
  56. 'readonly': 'readOnly',
  57. 'for': 'htmlFor',
  58. 'class': 'className',
  59. 'maxlength': 'maxLength',
  60. 'cellspacing': 'cellSpacing',
  61. 'cellpadding': 'cellPadding',
  62. 'rowspan': 'rowSpan',
  63. 'colspan': 'colSpan',
  64. 'usemap': 'useMap',
  65. 'frameborder': 'frameBorder',
  66. 'contenteditable': 'contentEditable'
  67. },
  68.  
  69. isArray = Array.isArray ||
  70. function(object){ return object instanceof Array }
  71.  
  72. /**
  73. * 元素是否匹配选择器
  74. * @param element
  75. * @param selector
  76. * @returns {*}
  77. */
  78. zepto.matches = function(element, selector) {
  79. //没参数,非元素,直接返回
  80. if (!selector || !element || element.nodeType !== ) return false
  81.  
  82. //如果浏览器支持MatchesSelector 直接调用
  83. var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
  84. element.oMatchesSelector || element.matchesSelector
  85. if (matchesSelector) return matchesSelector.call(element, selector)
  86.  
  87. //浏览器不支持MatchesSelector
  88. var match, parent = element.parentNode, temp = !parent
  89.  
  90. //元素没有父元素,存入到临时的div tempParent
  91. if (temp) (parent = tempParent).appendChild(element)
  92.  
  93. //再通过父元素来搜索此表达式。 找不到-1 找到有索引从0开始
  94. //注意 ~取反位运算符 作用是将值取负数再减1 如-1变成0 0变成-1
  95. match = ~zepto.qsa(parent, selector).indexOf(element)
  96.  
  97. //清理临时父节点
  98. temp && tempParent.removeChild(element)
  99.  
  100. //返回匹配
  101. return match
  102. }
  103.  
  104. /**
  105. * 获取对象类型
  106. * @param obj
  107. * @returns {*}
  108. */
  109. function type(obj) {
  110. return obj == null ? String(obj) :
  111. class2type[toString.call(obj)] || "object"
  112. }
  113.  
  114. function isFunction(value) { return type(value) == "function" }
  115. function isWindow(obj) { return obj != null && obj == obj.window }
  116. function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
  117. function isObject(obj) {
  118. return type(obj) == "object"
  119. }
  120. /**
  121. * 是否是纯粹对象 JSON/new Object
  122. * @param obj
  123. * @returns {*|boolean|boolean}
  124. */
  125. function isPlainObject(obj) {
  126. //是对象 非window 非new时需要传参的
  127. return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
  128. }
  129.  
  130. /**
  131. * 伪数组/数组判断
  132. * @param obj
  133. * @returns {boolean}
  134. */
  135. function likeArray(obj) { return typeof obj.length == 'number' }
  136.  
  137. /**
  138. * 清掉数组中的null/undefined
  139. * @param array
  140. * @returns {*}
  141. */
  142. function compact(array) { return filter.call(array, function(item){ return item != null }) }
  143.  
  144. /**
  145. * 返回一个数组副本
  146. * 利用空数组$.fn.concat.apply([], array) 合并新的数组,返回副本
  147. * @param array
  148. * @returns {*|Function|Function|Function|Function|Function|Zepto.fn.concat|Zepto.fn.concat|Zepto.fn.concat|Array|string}
  149. */
  150. function flatten(array) {
  151. return array.length > ? $.fn.concat.apply([], array) : array
  152. }
  153.  
  154. /**
  155. * 将'-'字符串转成驼峰格式
  156. * @param str
  157. * @returns {*|void}
  158. */
  159. camelize = function(str){
  160. return str.replace(/-+(.)?/g, function(match, chr){
  161. //匹配到-字符后的字母,转换为大写返回
  162. return chr ? chr.toUpperCase() : ''
  163. })
  164. }
  165.  
  166. /**
  167. * 字符串转换成浏览器可识别的 -拼接形式。 如background-color
  168. *
  169. * @param str
  170. * @returns {string}
  171. */
  172. function dasherize(str) {
  173. return str.replace(/::/g, '/') //将::替换成/
  174. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') //在大小写字符之间插入_,大写在前,比如AAAbb,得到AA_Abb
  175. .replace(/([a-z\d])([A-Z])/g, '$1_$2') //在大小写字符之间插入_,小写或数字在前,比如bbbAaa,得到bbb_Aaa
  176. .replace(/_/g, '-') //将_替换成-
  177. .toLowerCase() //转成小写
  178. }
  179. //数组去重,如果该条数据在数组中的位置与循环的索引值不相同,则说明数组中有与其相同的值
  180. uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
  181.  
  182. /**
  183. * 将参数变为正则表达式
  184. * @param name
  185. * @returns {*}
  186. */
  187. function classRE(name) {
  188. //classCache,缓存正则
  189. //TODO 缓存可以理解,但应该在重复使用第二次时再缓存吧,直接缓存?
  190. return name in classCache ?
  191. classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
  192. }
  193.  
  194. /**
  195. * 除了cssNumber指定的不需要加单位的,默认加上px
  196. * @param name
  197. * @param value
  198. * @returns {string}
  199. */
  200. function maybeAddPx(name, value) {
  201. return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
  202. }
  203.  
  204. /**
  205. * 获取元素的默认display属性
  206. * 是为了兼容什么?
  207. * @param nodeName
  208. * @returns {*}
  209. */
  210. function defaultDisplay(nodeName) {
  211. var element, display
  212. if (!elementDisplay[nodeName]) { //缓存里没有
  213.  
  214. element = document.createElement(nodeName)
  215. document.body.appendChild(element)
  216. display = getComputedStyle(element, '').getPropertyValue("display")
  217. element.parentNode.removeChild(element)
  218.  
  219. // display == "none",设置成blaock,即隐藏-显示
  220. display == "none" && (display = "block")
  221.  
  222. elementDisplay[nodeName] = display //TODO:缓存元素的默认display属性,缓存干嘛?
  223. }
  224. return elementDisplay[nodeName]
  225. }
  226.  
  227. /**
  228. * 获取元素的子节集
  229. * 原理:原生方法children 老的火狐不支持的,遍历childNodes
  230. * @param element
  231. * @returns {*}
  232. */
  233. function children(element) {
  234. return 'children' in element ?
  235. slice.call(element.children) :
  236. $.map(element.childNodes, function(node){ if (node.nodeType == ) return node })
  237. }
  238.  
  239. /**
  240. * 构造器
  241. * @param dom
  242. * @param selector
  243. * @constructor
  244. */
  245. function Z(dom, selector) {
  246. var i, len = dom ? dom.length :
  247. for (i = ; i < len; i++) this[i] = dom[i]
  248. this.length = len
  249. this.selector = selector || ''
  250. }
  251.  
  252. // `$.zepto.fragment` takes a html string and an optional tag name
  253. // to generate DOM nodes nodes from the given html string.
  254. // The generated DOM nodes are returned as an array.
  255. // This function can be overriden in plugins for example to make
  256. // it compatible with browsers that don't support the DOM fully.
  257. /**
  258. * 内部函数 HTML 转换成 DOM
  259. * 原理是 创建父元素,innerHTML转换
  260. * @param html html片段
  261. * @param name 容器标签名
  262. * @param propertie 附加的属性对象
  263. * @returns {*}
  264. */
  265. zepto.fragment = function(html, name, properties) {
  266. var dom, nodes, container
  267.  
  268. // A special case optimization for a single tag
  269. //如果是单个元素,创建dom
  270. //TODO
  271. // RegExp 是javascript中的一个内置对象。为正则表达式。
  272. // RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串,以此类推,RegExp.$2,RegExp.$3,..RegExp.$99总共可以有99个匹配
  273. if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$))
  274.  
  275. if (!dom) {
  276. //修正自闭合标签 如<div />,转换成<div></div>
  277. if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
  278. //给name取元素名
  279. if (name === undefined) name = fragmentRE.test(html) && RegExp.$
  280. //设置容器名,如果不是tr,tbody,thead,tfoot,td,th,则容器名为div
  281. //为什么设置容器,是严格按照HTML语法,虽然tr td th浏览器会会自动添加tbody
  282. if (!(name in containers)) name = '*'
  283.  
  284. container = containers[name] //创建容器
  285. container.innerHTML = '' + html //生成DOM
  286. //取容器的子节点,TODO:子节点集会返回
  287. dom = $.each(slice.call(container.childNodes), function(){
  288. container.removeChild(this) //把创建的子节点逐个删除
  289. })
  290. }
  291. //如果properties是对象,遍历它,将它设置成DOM的属性
  292. if (isPlainObject(properties)) {
  293. //转换成Zepto Obj,方便调用Zepto的方法
  294. nodes = $(dom)
  295. //遍历对象,设置属性
  296. $.each(properties, function(key, value) {
  297. //优先获取属性修正对象,通过修正对象读写值
  298. // methodAttributes包含'val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset',
  299. //TODO: 奇怪的属性
  300. if (methodAttributes.indexOf(key) > -) nodes[key](value)
  301. else nodes.attr(key, value)
  302. })
  303. }
  304.  
  305. //返回dom数组 如[div,div]
  306. return dom
  307. }
  308.  
  309. // `$.zepto.Z` swaps out the prototype of the given `dom` array
  310. // of nodes with `$.fn` and thus supplying all the Zepto functions
  311. // to the array. This method can be overriden in plugins.
  312. //入口函数?
  313. zepto.Z = function(dom, selector) {
  314. return new Z(dom, selector)
  315. }
  316.  
  317. // `$.zepto.isZ` should return `true` if the given object is a Zepto
  318. // collection. This method can be overriden in plugins.
  319. //判断给定的参数是否是Zepto集
  320. zepto.isZ = function(object) {
  321. return object instanceof zepto.Z
  322. }
  323.  
  324. // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
  325. // takes a CSS selector and an optional context (and handles various
  326. // special cases).
  327. // This method can be overriden in plugins.
  328. zepto.init = function(selector, context) {
  329. var dom
  330. // If nothing given, return an empty Zepto collection
  331. //未传参,undefined进行boolean转换,返回空Zepto对象
  332. if (!selector) return zepto.Z()
  333. // Optimize for string selectors
  334.  
  335. //selector是字符串,即css表达式
  336. else if (typeof selector == 'string') {
  337. //去前后空格
  338. selector = selector.trim()
  339. // If it's a html fragment, create nodes from it
  340. // Note: In both Chrome 21 and Firefox 15, DOM error 12
  341. // is thrown if the fragment doesn't begin with <
  342. //如果是<开头 >结尾 基本的HTML代码时
  343. if (selector[] == '<' && fragmentRE.test(selector))
  344. //调用片段生成dom
  345. dom = zepto.fragment(selector, RegExp.$, context), selector = null
  346. // If there's a context, create a collection on that context first, and select
  347. // nodes from there
  348. //如果传递了上下文,在上下文中查找元素
  349. else if (context !== undefined) return $(context).find(selector)
  350. // If it's a CSS selector, use it to select nodes.
  351. //通过css表达式查找元素
  352. else dom = zepto.qsa(document, selector)
  353. }
  354. // If a function is given, call it when the DOM is ready
  355. //如果selector是函数,则在DOM ready的时候执行它
  356. else if (isFunction(selector)) return $(document).ready(selector)
  357. // If a Zepto collection is given, just return it
  358. //如果selector是一个Zepto对象,返回它自己
  359. else if (zepto.isZ(selector)) return selector
  360. else {
  361. // normalize array if an array of nodes is given
  362. //如果selector是数组,过滤null,undefined
  363. if (isArray(selector)) dom = compact(selector)
  364. // Wrap DOM nodes.
  365. //如果selector是对象,TODO://转换为数组? 它应是DOM; 注意DOM节点的typeof值也是object,所以在里面还要再进行一次判断
  366. else if (isObject(selector))
  367. dom = [selector], selector = null
  368. // If it's a html fragment, create nodes from it
  369. //如果selector是复杂的HTML代码,调用片段换成DOM节点
  370. else if (fragmentRE.test(selector))
  371. dom = zepto.fragment(selector.trim(), RegExp.$, context), selector = null
  372. // If there's a context, create a collection on that context first, and select
  373. // nodes from there
  374. //如果存在上下文context,仍在上下文中查找selector
  375. else if (context !== undefined) return $(context).find(selector)
  376. // And last but no least, if it's a CSS selector, use it to select nodes.
  377. //如果没有给定上下文,在document中查找selector
  378. else dom = zepto.qsa(document, selector)
  379. }
  380. // create a new Zepto collection from the nodes found
  381. //将查询结果转换成Zepto对象
  382. return zepto.Z(dom, selector)
  383. }
  384.  
  385. // `$` will be the base `Zepto` object. When calling this
  386. // function just call `$.zepto.init, which makes the implementation
  387. // details of selecting nodes and creating Zepto collections
  388. // patchable in plugins.
  389. $ = function(selector, context){
  390. return zepto.init(selector, context)
  391. }
  392.  
  393. /**
  394. * 内部方法:用户合并一个或多个对象到第一个对象
  395. * @param target 目标对象 对象都合并到target里
  396. * @param source 合并对象
  397. * @param deep 是否执行深度合并
  398. */
  399. function extend(target, source, deep) {
  400. for (key in source)
  401. //如果深度合并
  402. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  403. //如果要合并的属性是对象,但target对应的key非对象
  404. if (isPlainObject(source[key]) && !isPlainObject(target[key]))
  405. target[key] = {}
  406. //如果要合并的属性是数组,但target对应的key非数组
  407. if (isArray(source[key]) && !isArray(target[key]))
  408. target[key] = []
  409.  
  410. //执行递归合并
  411. extend(target[key], source[key], deep)
  412. }
  413. //不是深度合并,直接覆盖
  414. //TODO: 合并不显得太简单了?
  415. else if (source[key] !== undefined) target[key] = source[key]
  416. }
  417.  
  418. // Copy all but undefined properties from one or more
  419. // objects to the `target` object.
  420. /**
  421. * 对外方法
  422. * 合并
  423. * @param target
  424. * @returns {*}
  425. */
  426. $.extend = function(target){
  427. var deep, //是否执行深度合并
  428. args = slice.call(arguments, )//arguments[0]是target,被合并对象,或为deep
  429. if (typeof target == 'boolean') {
  430. //第一个参数为boolean值时,表示是否深度合并
  431. deep = target
  432. target = args.shift() //target取第二个参数
  433. }
  434. //遍历后面的参数,都合并到target上
  435. args.forEach(function(arg){ extend(target, arg, deep) })
  436. return target
  437. }
  438.  
  439. // `$.zepto.qsa` is Zepto's CSS selector implementation which
  440. // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
  441. // This method can be overriden in plugins.
  442. /**
  443. * 通过选择器表达式查找DOM
  444. * 原理 判断下选择器的类型(id/class/标签/表达式)
  445. * 使用对应方法getElementById getElementsByClassName getElementsByTagName querySelectorAll 查找
  446. * @param element
  447. * @param selector
  448. * @returns {Array}
  449. */
  450. zepto.qsa = function(element, selector){
  451. var found,
  452. maybeID = selector[] == '#',//ID标识
  453. maybeClass = !maybeID && selector[] == '.',//class 标识
  454. //是id/class,就取'#/.'后的字符串,如‘#test’取‘test'
  455. nameOnly = maybeID || maybeClass ? selector.slice() : selector,
  456. isSimple = simpleSelectorRE.test(nameOnly) //TODO:是否为单个选择器 没有空格
  457. return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
  458. //通过getElementById查找DOM,找到返回[dom],找不到返回[]
  459. ( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
  460. //当element不为元素节点或document fragment时,返回空
  461. //元素element 1 属性attr 2 文本text 3 注释comments 8 文档document 9 片段 fragment 11
  462. (element.nodeType !== && element.nodeType !== && element.nodeType !== ) ? [] :
  463. slice.call(
  464. //如果是class,通过getElementsByClassName查找DOM,
  465. isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
  466. maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
  467. element.getElementsByTagName(selector) : // Or a tag //如果是标签名,调用getElementsByTagName
  468. //最后调用querySelectorAll
  469. element.querySelectorAll(selector) // Or it's not simple, and we need to query all
  470. )
  471. }
  472.  
  473. /**
  474. * 在元素集中过滤某些元素
  475. * @param nodes
  476. * @param selector
  477. * @returns {*|HTMLElement}
  478. */
  479. function filtered(nodes, selector) {
  480. return selector == null ? $(nodes) : $(nodes).filter(selector)
  481. }
  482.  
  483. /**
  484. * 父元素是否包含子元素
  485. * @type {Function}
  486. */
  487. $.contains = document.documentElement.contains ?
  488. function(parent, node) {
  489. //父元素
  490. return parent !== node && parent.contains(node)
  491. } :
  492. function(parent, node) {
  493. while (node && (node = node.parentNode))
  494. if (node === parent) return true
  495. return false
  496. }
  497.  
  498. /**
  499. * 处理 arg为函数/值
  500. * 为函数,返回函数返回值
  501. * 为值,返回值
  502. * @param context
  503. * @param arg
  504. * @param idx
  505. * @param payload
  506. * @returns {*}
  507. */
  508. function funcArg(context, arg, idx, payload) {
  509. return isFunction(arg) ? arg.call(context, idx, payload) : arg
  510. }
  511.  
  512. /**
  513. * 设置属性
  514. * @param node
  515. * @param name
  516. * @param value
  517. */
  518. function setAttribute(node, name, value) {
  519. //value为null/undefined,处理成删除,否则设值
  520. value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
  521. }
  522.  
  523. // access className property while respecting SVGAnimatedString
  524. /**
  525. * 对SVGAnimatedString的兼容?
  526. * @param node
  527. * @param value
  528. * @returns {*}
  529. */
  530. function className(node, value){
  531. var klass = node.className || '',
  532. svg = klass && klass.baseVal !== undefined
  533.  
  534. if (value === undefined) return svg ? klass.baseVal : klass
  535. svg ? (klass.baseVal = value) : (node.className = value) //class设值
  536. }
  537.  
  538. // "true" => true
  539. // "false" => false
  540. // "null" => null
  541. // "42" => 42
  542. // "42.5" => 42.5
  543. // "08" => "08"
  544. // JSON => parse if valid
  545. // String => self
  546. /**
  547. * 序列化值 把自定义数据读出来时做应该的转换,$.data()方法使用
  548. * @param value
  549. * @returns {*}
  550. */
  551. function deserializeValue(value) {
  552. try {
  553. return value ?
  554. value == "true" ||
  555. ( value == "false" ? false :
  556. value == "null" ? null :
  557. +value + "" == value ? +value :
  558. /^[\[\{]/.test(value) ? $.parseJSON(value) :
  559. value )
  560. : value
  561. } catch(e) {
  562. return value
  563. }
  564. }
  565.  
  566. $.type = type
  567. $.isFunction = isFunction
  568. $.isWindow = isWindow
  569. $.isArray = isArray
  570. $.isPlainObject = isPlainObject
  571.  
  572. /**
  573. * 空对象
  574. * @param obj
  575. * @returns {boolean}
  576. */
  577. $.isEmptyObject = function(obj) {
  578. var name
  579. for (name in obj) return false
  580. return true
  581. }
  582.  
  583. /**
  584. * 获取在数组中的索引
  585. * @param elem
  586. * @param array
  587. * @param i
  588. * @returns {number}
  589. */
  590. $.inArray = function(elem, array, i){
  591. //i从第几个开始搜索
  592. return emptyArray.indexOf.call(array, elem, i)
  593. }
  594.  
  595. //将字符串转成驼峰格式
  596. $.camelCase = camelize
  597. //去字符串头尾空格
  598. $.trim = function(str) {
  599. return str == null ? "" : String.prototype.trim.call(str)
  600. }
  601.  
  602. // plugin compatibility
  603. $.uuid =
  604. $.support = { }
  605. $.expr = { }
  606. $.noop = function() {}
  607.  
  608. /**
  609. * 内部方法
  610. * 遍历对象/数组 在每个元素上执行回调,将回调的返回值放入一个新的数组返回
  611. * @param elements
  612. * @param callback
  613. * @returns {*}
  614. */
  615. $.map = function(elements, callback){
  616. var value, values = [], i, key
  617. //如果被遍历的数据是数组或者Zepto(伪数组)
  618. if (likeArray(elements))
  619. for (i = ; i < elements.length; i++) {
  620. value = callback(elements[i], i)
  621. if (value != null) values.push(value)
  622. }
  623. else
  624. //如果是对象
  625. for (key in elements) {
  626. value = callback(elements[key], key)
  627. if (value != null) values.push(value)
  628. }
  629. return flatten(values)
  630. }
  631.  
  632. /**
  633. * 以集合每一个元素作为上下文,来执行回调函数
  634. * @param elements
  635. * @param callback
  636. * @returns {*}
  637. */
  638. $.each = function(elements, callback){
  639. var i, key
  640. if (likeArray(elements)) { //数组、伪数组
  641. for (i = ; i < elements.length; i++)
  642. if (callback.call(elements[i], i, elements[i]) === false) return elements
  643. } else {
  644. for (key in elements) //对象
  645. if (callback.call(elements[key], key, elements[key]) === false) return elements
  646. }
  647.  
  648. return elements
  649. }
  650.  
  651. /**
  652. * 查找数组满足过滤函数的元素
  653. * @param elements
  654. * @param callback
  655. * @returns {*}
  656. */
  657. $.grep = function(elements, callback){
  658. return filter.call(elements, callback)
  659. }
  660.  
  661. if (window.JSON) $.parseJSON = JSON.parse
  662.  
  663. //填充class2type的值
  664. $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  665. class2type[ "[object " + name + "]" ] = name.toLowerCase()
  666. })
  667.  
  668. // Define methods that will be available on all
  669. // Zepto collections
  670. //针对DOM的一些操作
  671. $.fn = {
  672. constructor: zepto.Z,
  673. length: ,
  674.  
  675. // Because a collection acts like an array
  676. // copy over these useful array functions.
  677. forEach: emptyArray.forEach,
  678. reduce: emptyArray.reduce,
  679. push: emptyArray.push,
  680. sort: emptyArray.sort,
  681. splice: emptyArray.splice,
  682. indexOf: emptyArray.indexOf,
  683. /**
  684. * 合并多个数组
  685. * @returns {*}
  686. */
  687. concat: function(){
  688. var i, value, args = []
  689. for (i = ; i < arguments.length; i++) {
  690. value = arguments[i]
  691. args[i] = zepto.isZ(value) ? value.toArray() : value
  692. }
  693. return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)
  694. },
  695.  
  696. // `map` and `slice` in the jQuery API work differently
  697. // from their array counterparts
  698. /**
  699. * 遍历对象/数组 在每个元素上执行回调,将回调的返回值放入一个新的Zepto返回
  700. * @param fn
  701. * @returns {*|HTMLElement}
  702. */
  703. map: function(fn){
  704. return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
  705. },
  706. /**
  707. * slice包装成Zepto
  708. * @returns {*|HTMLElement}
  709. */
  710. slice: function(){
  711. return $(slice.apply(this, arguments))
  712. },
  713.  
  714. /**
  715. * 当DOM载入就绪时,绑定回调
  716. * 如 $(function(){}) $(document).ready(function(){
  717. // 在这里写你的代码
  718. * @param callback
  719. * @returns {*}
  720. */
  721. ready: function(callback){
  722. // need to check if document.body exists for IE as that browser reports
  723. // document ready when it hasn't yet created the body element
  724.  
  725. //如果已经ready
  726. if (readyRE.test(document.readyState) && document.body) callback($)
  727.  
  728. //监听DOM已渲染完毕事件
  729. else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
  730. return this
  731. },
  732. /**
  733. * 取Zepto中指定索引的值
  734. * @param idx 可选,不传时,将Zetpo转换成数组
  735. * @returns {*}
  736. */
  737. get: function(idx){
  738. return idx === undefined ? slice.call(this) : this[idx >= ? idx : idx + this.length]
  739. },
  740. /**
  741. * 将Zepto(伪数组)转换成数组
  742. * 原理是 伪数组转换成数组oa = {0:'a',length:1};Array.prototype.slice.call(oa);
  743. * 数组转换伪数组 var obj = {}, push = Array.prototype.push; push.apply(obj,[1,2]);
  744. * @returns {*}
  745. */
  746. toArray: function(){
  747. return this.get()
  748. },
  749. //获取集合长度
  750. size: function(){
  751. return this.length
  752. },
  753. /**
  754. * 删除元素集
  755. * 原理 parentNode.removeChild
  756. * @returns {*}
  757. */
  758. remove: function(){
  759. //遍历到其父元素 removeChild
  760. return this.each(function(){
  761. if (this.parentNode != null)
  762. this.parentNode.removeChild(this)
  763. })
  764. },
  765. //遍历集合,将集合中的每一项放入callback中进行处理,去掉结果为false的项,注意这里的callback如果明确返回false
  766. //那么就会停止循环了
  767. /**
  768. * 遍历Zepto,在每个元素上执行回调函数
  769. * @param callback
  770. * @returns {*}
  771. */
  772. each: function(callback){
  773.  
  774. emptyArray.every.call(this, function(el, idx){
  775. //el:元素,idx:下标 传递给callback(idx,el)
  776. return callback.call(el, idx, el) !== false
  777. })
  778. return this
  779. },
  780.  
  781. /**
  782. * 过滤,返回处理结果为true的记录
  783. * @param selector
  784. * @returns {*}
  785. */
  786. filter: function(selector){
  787. //this.not(selector)取到需要排除的集合,第二次再取反(这个时候this.not的参数就是一个集合了),得到想要的集合
  788. if (isFunction(selector)) return this.not(this.not(selector))
  789.  
  790. //filter收集返回结果为true的记录
  791. return $(filter.call(this, function(element){
  792. //当element与selector匹配,则收集
  793. return zepto.matches(element, selector)
  794. }))
  795. },
  796. //将由selector获取到的结果追加到当前集合中
  797. add: function(selector,context){
  798. //追加并去重
  799. return $(uniq(this.concat($(selector,context))))
  800. },
  801. //返回集合中的第1条记录是否与selector匹配
  802. is: function(selector){
  803. return this.length > && zepto.matches(this[], selector)
  804. },
  805. //排除集合里满足条件的记录,接收参数为:css选择器,function, dom ,nodeList
  806. not: function(selector){
  807. var nodes=[]
  808. //当selector为函数时,safari下的typeof odeList也是function,所以这里需要再加一个判断selector.call !== undefined
  809. if (isFunction(selector) && selector.call !== undefined)
  810. this.each(function(idx){
  811. //注意这里收集的是selector.call(this,idx)返回结果为false的时候记录
  812. if (!selector.call(this,idx)) nodes.push(this)
  813. })
  814. else {
  815. //当selector为字符串的时候,对集合进行筛选,也就是筛选出集合中满足selector的记录
  816. var excludes = typeof selector == 'string' ? this.filter(selector) :
  817. //当selector为nodeList时执行slice.call(selector),注意这里的isFunction(selector.item)是为了排除selector为数组的情况
  818. //当selector为css选择器,执行$(selector)
  819. (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
  820. this.forEach(function(el){
  821. //筛选出不在excludes集合里的记录,达到排除的目的
  822. if (excludes.indexOf(el) < ) nodes.push(el)
  823. })
  824. }
  825. return $(nodes)//由于上面得到的结果是数组,这里需要转成zepto对象,以便继承其它方法,实现链写
  826. },
  827.  
  828. /*
  829. 接收node和string作为参数,给当前集合筛选出包含selector的集合
  830. isObject(selector)是判断参数是否是node,因为typeof node == 'object'
  831. 当参数为node时,只需要判读当前记当里是否包含node节点即可
  832. 当参数为string时,则在当前记录里查询selector,如果长度为0,则为false,filter函数就会过滤掉这条记录,否则保存该记录
  833. */
  834. has: function(selector){
  835. return this.filter(function(){
  836. return isObject(selector) ?
  837. $.contains(this, selector) :
  838. $(this).find(selector).size()
  839. })
  840. },
  841. /**
  842. * 取Zepto中的指定索引的元素,再包装成Zepto返回
  843. * @param idx
  844. * @returns {*}
  845. */
  846. eq: function(idx){
  847. return idx === - ? this.slice(idx) : this.slice(idx, + idx + )
  848. },
  849. /*
  850. 取第一条$(元素)
  851. */
  852. first: function(){
  853. var el = this[] //取第一个元素
  854.  
  855. //非$对象,转换成$,
  856. //如果element,isObject会判断为true。zepto也判断为true,都会重新转换成$(el)
  857. //TODO:这里是bug?
  858. return el && !isObject(el) ? el : $(el)
  859. },
  860. /*
  861. 取最后一条$(元素)
  862. */
  863. last: function(){
  864. var el = this[this.length - ]
  865. return el && !isObject(el) ? el : $(el)
  866. },
  867. /*
  868. 在当前集合中查找selector,selector可以是集合,选择器,以及节点
  869. */
  870. find: function(selector){
  871. var result, $this = this
  872. //如果selector为node或者zepto集合时
  873. if (!selector) result = $()
  874. //遍历selector,筛选出父级为集合中记录的selector
  875. else if (typeof selector == 'object')
  876. result = $(selector).filter(function(){
  877. var node = this
  878. //如果$.contains(parent, node)返回true,则emptyArray.some也会返回true,外层的filter则会收录该条记录
  879. return emptyArray.some.call($this, function(parent){
  880. return $.contains(parent, node)
  881. })
  882. })
  883. //如果selector是css选择器
  884. //如果当前集合长度为1时,调用zepto.qsa,将结果转成zepto对象
  885. else if (this.length == ) result = $(zepto.qsa(this[], selector))
  886. //如果长度大于1,则调用map遍历
  887. else result = this.map(function(){ return zepto.qsa(this, selector) })
  888. return result
  889. },
  890.  
  891. /**
  892. * 取最近的满足selector选择器的祖先元素
  893. * @param selector
  894. * @param context
  895. * @returns {*|HTMLElement}
  896. */
  897. closest: function(selector, context){
  898. var node = this[], collection = false
  899. if (typeof selector == 'object') collection = $(selector)
  900.  
  901. //node递归parentNode,直到满足selector表达式,返回$
  902. while (node && !(collection ? collection.indexOf(node) >= : zepto.matches(node, selector)))
  903. //当node 不是context,document的时候,取node.parentNode
  904. node = node !== context && !isDocument(node) && node.parentNode
  905. return $(node)
  906. },
  907. /**
  908. * 取得所有匹配的祖先元素
  909. * @param selector
  910. * @returns {*}
  911. */
  912. parents: function(selector){
  913. var ancestors = [], nodes = this
  914.  
  915. //先取得所有祖先元素
  916. while (nodes.length > ) //到不再有父元素时,退出循环
  917. //取得所有父元素 //nodes被再赋值为收集到的父元素数组
  918. nodes = $.map(nodes, function(node){
  919. //获取父级, isDocument(node) 到Document为止
  920. // ancestors.indexOf(node)去重复
  921. if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < ) {
  922. ancestors.push(node)
  923. //收集已经获取到的父级元素,用于去重复
  924. return node
  925. }
  926. })
  927.  
  928. //筛选出符合selector的祖先元素
  929. return filtered(ancestors, selector)
  930. },
  931. /**
  932. * 获取父元素
  933. * @param selector
  934. * @returns {*|HTMLElement}
  935. */
  936. parent: function(selector){
  937. return filtered(uniq(this.pluck('parentNode')), selector)
  938. },
  939. /**
  940. * 获取子元素集
  941. * @param selector
  942. * @returns {*|HTMLElement}
  943. */
  944. children: function(selector){
  945. return filtered(this.map(function(){ return children(this) }), selector)
  946. },
  947. /**
  948. * 获取iframe的docment,或子节集
  949. * @returns {*|HTMLElement}
  950. */
  951. contents: function() {
  952. return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
  953. },
  954. /**
  955. * 获取兄弟节点集
  956. * @param selector
  957. * @returns {*|HTMLElement}
  958. */
  959. siblings: function(selector){
  960. return filtered(this.map(function(i, el){
  961. //到其父元素取得所有子节点,再排除本身
  962. return filter.call(children(el.parentNode), function(child){ return child!==el })
  963. }), selector)
  964. },
  965. /**
  966. * 移除所有子元素
  967. * 原理: innerHTML = ''
  968. * @returns {*}
  969. */
  970. empty: function(){
  971. return this.each(function(){ this.innerHTML = '' })
  972. },
  973.  
  974. /**
  975. * 根据是否存在此属性来获取当前集合
  976. * @param property
  977. * @returns {*}
  978. */
  979. pluck: function(property){
  980. return $.map(this, function(el){ return el[property] })
  981. },
  982. /**
  983. * 展示
  984. * @returns {*}
  985. */
  986. show: function(){
  987. return this.each(function(){
  988. //清除内联样式display="none"
  989. this.style.display == "none" && (this.style.display = '')
  990. //计算样式display为none时,重赋显示值
  991. if (getComputedStyle(this, '').getPropertyValue("display") == "none")
  992. this.style.display = defaultDisplay(this.nodeName)
  993. //defaultDisplay是获取元素默认display的方法
  994. })
  995. },
  996. /**
  997. * 替换元素
  998. * 原理 before
  999. * @param newContent
  1000. * @returns {*}
  1001. */
  1002. replaceWith: function(newContent){
  1003. //将要替换内容插到被替换内容前面,然后删除被替换内容
  1004. return this.before(newContent).remove()
  1005. },
  1006. /**
  1007. * 匹配的每条元素都被单个元素包裹
  1008. * @param structure fun/
  1009. * @returns {*}
  1010. */
  1011. wrap: function(structure){
  1012. var func = isFunction(structure)
  1013. if (this[] && !func) //如果structure是字符串
  1014. //直接转成DOM
  1015. var dom = $(structure).get(),
  1016. //如果DOM已存在(通过在文档中读parentNode判断),或$集不止一条,需要克隆。避免DOM被移动位置
  1017. clone = dom.parentNode || this.length >
  1018.  
  1019. return this.each(function(index){
  1020. //递归包裹克隆的DOM
  1021. $(this).wrapAll(
  1022. func ? structure.call(this, index) :
  1023. clone ? dom.cloneNode(true) : dom //克隆包裹
  1024. )
  1025. })
  1026. },
  1027. /**
  1028. * 将所有匹配的元素用单个元素包裹起来
  1029. * @param structure 包裹内容
  1030. * @returns {*}
  1031. */
  1032. wrapAll: function(structure){
  1033. if (this[]) {
  1034. //包裹内容插入到第一个元素前
  1035. $(this[]).before(structure = $(structure))
  1036. var children
  1037. // drill down to the inmost element
  1038. // drill down to the inmost element
  1039. //取包裹内容里的第一个子元素的最里层
  1040. while ((children = structure.children()).length) structure = children.first()
  1041.  
  1042. //将当前$插入到最里层元素里
  1043. $(structure).append(this)
  1044. }
  1045. return this
  1046. },
  1047. /**
  1048. * 包裹到里面 将每一个匹配元素的子内容(包括文本节点)用HTML包裹起来
  1049. * 原理 获取节点的内容
  1050. * @param structure
  1051. * @returns {*}
  1052. */
  1053. wrapInner: function(structure){
  1054. var func = isFunction(structure)
  1055. return this.each(function(index){
  1056. //遍历获取节点的内容,然后用structure将内容包裹
  1057. var self = $(this), contents = self.contents(),
  1058. dom = func ? structure.call(this, index) : structure
  1059. contents.length ? contents.wrapAll(dom) : self.append(dom) //内容不存在,直接添加structure
  1060. })
  1061. },
  1062. /**
  1063. * 去包裹 移除元素的父元素
  1064. * 原理: 子元素替换父元素
  1065. * @returns {*}
  1066. */
  1067. unwrap: function(){
  1068. this.parent().each(function(){
  1069. $(this).replaceWith($(this).children())
  1070. })
  1071. return this
  1072. },
  1073. /**
  1074. * 复制元素的副本 TODO:事件、自定义数据会复制吗?
  1075. * 原理 cloneNode
  1076. * @returns {*|HTMLElement}
  1077. */
  1078. clone: function(){
  1079. return this.map(function(){ return this.cloneNode(true) })
  1080. },
  1081. /**
  1082. * 隐藏
  1083. * @returns {*}
  1084. */
  1085. hide: function(){
  1086. return this.css("display", "none")
  1087. },
  1088. /**
  1089. * 不给参数,切换显示隐藏
  1090. * 给参数 true show false hide
  1091. * @param setting
  1092. * @returns {*}
  1093. */
  1094. toggle: function(setting){
  1095. return this.each(function(){
  1096.  
  1097. var el = $(this)
  1098. ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
  1099. })
  1100. },
  1101. /**
  1102. * 筛选前面所有的兄弟元素
  1103. * @param selector
  1104. * @returns {*}
  1105. */
  1106. prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
  1107.  
  1108. /**
  1109. * 筛选后面所有的兄弟元素
  1110. * @param selector
  1111. * @returns {*}
  1112. */
  1113. next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
  1114.  
  1115. /**
  1116. * 读写元素HTML内容
  1117. * 原理 通过innerHTML读内容,append()写内容
  1118. * @param html
  1119. * @returns {*|string|string|string|string|string}
  1120. */
  1121. html: function(html){
  1122. return in arguments ?
  1123. this.each(function(idx){
  1124. var originHtml = this.innerHTML //记录原始的innerHTMl
  1125. //如果参数html是字符串直接插入到记录中,
  1126. //如果是函数,则将当前记录作为上下文,调用该函数,且传入该记录的索引和原始innerHTML作为参数
  1127. $(this).empty().append( funcArg(this, html, idx, originHtml) )
  1128. }) :
  1129. ( in this ? this[].innerHTML : null)
  1130. },
  1131. /**
  1132. * 读写元素文本内容
  1133. * 原理: 通过 textContent 读写文本
  1134. * @param text
  1135. * @returns {*}
  1136. */
  1137. text: function(text){
  1138. return in arguments ?
  1139. this.each(function(idx){ //传参遍历写入
  1140. var newText = funcArg(this, text, idx, this.textContent)
  1141. this.textContent = newText == null ? '' : ''+newText
  1142. }) :
  1143. ( in this ? this[].textContent : null) //未传参读
  1144. },
  1145.  
  1146. /**
  1147. * 元素的HTML属性读写
  1148. * 读:原理是getAttribute
  1149. * 写:原理是setAttribute
  1150. * @param name
  1151. * @param value
  1152. * @returns {undefined}
  1153. */
  1154. attr: function(name, value){
  1155. var result
  1156. //仅有name,且为字符串时,表示读
  1157. return (typeof name == 'string' && !( in arguments)) ?
  1158. //$是空的 或里面的元素非元素,返回undefined
  1159. (!this.length || this[].nodeType !== ? undefined :
  1160. //直接用getAttribute(name)读,
  1161. (!(result = this[].getAttribute(name)) && name in this[]) ? this[][name] : result
  1162. ) : //否则是写,不管name为对象{k:v},或name value 都存在
  1163. this.each(function(idx){
  1164. if (this.nodeType !== ) return //非元素
  1165. //如果name为对象,批量设置属性
  1166. if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
  1167. //处理value为函数/null/undefined的情况
  1168. else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
  1169. })
  1170. },
  1171. /**
  1172. * 元素的删除
  1173. * @param name 单个值 空格分隔
  1174. * @returns {*}
  1175. */
  1176. removeAttr: function(name){
  1177. return this.each(
  1178. function(){
  1179. this.nodeType === && name.split(' ').forEach(
  1180. function(attribute){
  1181. //不传value,会直接调用removeAttribute删除属性
  1182. setAttribute(this, attribute)
  1183. }, this)
  1184. })
  1185. },
  1186. //获取第一条数据的指定的name属性或者给每条数据添加自定义属性,注意和setAttribute的区别
  1187.  
  1188. /**
  1189. * 元素的DOM属性读写
  1190. * 原理:Element[name] 操作
  1191. * @param name
  1192. * @param value
  1193. * @returns {*}
  1194. */
  1195. prop: function(name, value){
  1196. //优先读取修正属性,DOM的两字母属性都是驼峰格式
  1197. name = propMap[name] || name
  1198. //没有给定value时,为获取,给定value则给每一条数据添加,value可以为值也可以是一个返回值的函数
  1199. return ( in arguments) ?
  1200. //有value,遍历写入
  1201. this.each(function(idx){
  1202. this[name] = funcArg(this, value, idx, this[name])
  1203. }) :
  1204. //读第一个元素
  1205. (this[] && this[][name])
  1206. },
  1207.  
  1208. /**
  1209. * 设置自定义数据
  1210. * 注意与jQuery的区别,jQuery可以读写任何数据类型。这里原理是H5的data-,或直接setAttribute/getAttribute,只能读写字符串
  1211. * @param name
  1212. * @param value
  1213. * @returns {*}
  1214. */
  1215. data: function(name, value){
  1216. var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()
  1217.  
  1218. var data = ( in arguments) ?
  1219. this.attr(attrName, value) :
  1220. this.attr(attrName)
  1221.  
  1222. return data !== null ? deserializeValue(data) : undefined
  1223. },
  1224. /**
  1225. * 适合表单元素读写
  1226. * 写: 写入每个元素 element.value
  1227. * 读: 读第一个元素
  1228. * @param value 值/函数
  1229. * @returns {*}
  1230. */
  1231. val: function(value){
  1232. return in arguments ?
  1233. //只有一个参数是写,
  1234. this.each(function(idx){
  1235. this.value = funcArg(this, value, idx, this.value)
  1236. }) :
  1237. //如果是读
  1238. (this[] && (this[].multiple ? //对多选的select的兼容处理,返回一个包含被选中的option的值的数组
  1239. $(this[]).find('option').filter(function(){ return this.selected }).pluck('value') :
  1240. this[].value)
  1241. )
  1242. },
  1243. /**
  1244. * 读/写坐标 距离文档document的偏移值
  1245. * 原理: 读 getBoundingClientRect视窗坐标-页面偏移 写:坐标-父元素坐标
  1246. * @param coordinates
  1247. * @returns {*}
  1248. */
  1249. offset: function(coordinates){
  1250. //写入坐标
  1251. if (coordinates) return this.each(function(index){
  1252. var $this = $(this),
  1253. //如果coordinates是函数,执行函数,
  1254. coords = funcArg(this, coordinates, index, $this.offset()),
  1255. //取父元素坐标
  1256. parentOffset = $this.offsetParent().offset(),
  1257. //计算出合理的坐标
  1258. props = {
  1259. top: coords.top - parentOffset.top,
  1260. left: coords.left - parentOffset.left
  1261. }
  1262. //修正postin static-relative
  1263. if ($this.css('position') == 'static') props['position'] = 'relative'
  1264.  
  1265. //写入样式
  1266. $this.css(props)
  1267. })
  1268. //读取坐标 取第一个元素的坐标
  1269. if (!this.length) return null
  1270. //如果父元素是document
  1271. if (!$.contains(document.documentElement, this[]))
  1272. return {top: , left: }
  1273.  
  1274. //读取到元素相对于页面视窗的位置
  1275. var obj = this[].getBoundingClientRect()
  1276.  
  1277. //window.pageYOffset就是类似Math.max(document.documentElement.scrollTop||document.body.scrollTop)
  1278. return {
  1279. left: obj.left + window.pageXOffset, //文档水平滚动偏移
  1280. top: obj.top + window.pageYOffset, //文档垂直滚动偏移 pageYOffset和scrollTop的区别是?
  1281. width: Math.round(obj.width),
  1282. height: Math.round(obj.height)
  1283. }
  1284. },
  1285. /**
  1286. * 读写样式 写:内联样式 读:计算样式
  1287. * 原理 读:elment[style]/getComputedStyle, 写 this.style.cssText 行内样式设值
  1288. * @param property String/Array/Fun
  1289. * @param value
  1290. * @returns {*}
  1291. */
  1292. css: function(property, value){
  1293. //只有一个传参,读
  1294. if (arguments.length < ) {
  1295. var computedStyle, element = this[]
  1296. if(!element) return
  1297. //getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读
  1298. //读到计算样式
  1299. computedStyle = getComputedStyle(element, '')
  1300. //设置样式
  1301. if (typeof property == 'string')// 字符串
  1302. //优先读行内样式,再读计算样式,行内样式级别最高? TODO:似乎有bug,如果设置了!important 呢
  1303. return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
  1304. else if (isArray(property)) { //数组
  1305. var props = {}
  1306. $.each(property, function(_, prop){ //遍历读取每一条样式,存入JSON,返回
  1307. props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
  1308. })
  1309. return props
  1310. }
  1311. }
  1312.  
  1313. //如果是写
  1314. var css = ''
  1315. if (type(property) == 'string') {
  1316. if (!value && value !== ) //null,undefined时,删掉样式
  1317. this.each(function(){
  1318. //删除 dasherize是将字符串转换成css属性(background-color格式)
  1319. this.style.removeProperty(dasherize(property))
  1320. })
  1321. else
  1322. //‘-’格式值 + px单位
  1323. css = dasherize(property) + ":" + maybeAddPx(property, value)
  1324. } else {
  1325. for (key in property) //是对象时
  1326. if (!property[key] && property[key] !== )
  1327. //当property[key]的值为null/undefined,删除属性
  1328. this.each(function(){ this.style.removeProperty(dasherize(key)) })
  1329. else
  1330. //‘-’格式值 + px单位
  1331. css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
  1332. }
  1333.  
  1334. //设值 //TODO: this.style.cssText += 未考虑去重了
  1335. return this.each(function(){ this.style.cssText += ';' + css })
  1336. },
  1337. index: function(element){
  1338. //这里的$(element)[0]是为了将字符串转成node,因为this是个包含node的数组
  1339. //当不指定element时,取集合中第一条记录在其父节点的位置
  1340. //this.parent().children().indexOf(this[0])这句很巧妙,和取第一记录的parent().children().indexOf(this)相同
  1341. return element ? this.indexOf($(element)[]) : this.parent().children().indexOf(this[])
  1342. },
  1343. /**
  1344. * 是否含有指定的类样式
  1345. * @param name
  1346. * @returns {boolean}
  1347. */
  1348. hasClass: function(name){
  1349. if (!name) return false
  1350. //some ES5的新方法 有一个匹配,即返回true 。
  1351. return emptyArray.some.call(this, function(el){
  1352. //this是classRE(name)生成的正则
  1353. return this.test(className(el))
  1354. }, classRE(name))
  1355. },
  1356. /**
  1357. * 增加一个或多个类名
  1358. * @param name 类名/空格分隔的类名/函数
  1359. * @returns {*}
  1360. */
  1361. addClass: function(name){
  1362. if (!name) return this
  1363.  
  1364. //遍历增加
  1365. return this.each(function(idx){
  1366. //已存在,返回
  1367. if (!('className' in this)) return
  1368. classList = []
  1369. var cls = className(this), newName = funcArg(this, name, idx, cls) //修正类名,处理name是函数,SVG动画兼容的情况
  1370.  
  1371. //多个类,空格分隔为数组
  1372. newName.split(/\s+/g).forEach(function(klass){
  1373. if (!$(this).hasClass(klass)) classList.push(klass)
  1374. }, this)
  1375.  
  1376. //设值
  1377. classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
  1378. })
  1379. },
  1380. /**
  1381. *删除一个或多个类名 同addClass
  1382. * 原理: className.repalce 替换撒谎年初
  1383. * @param name 类名/空格分隔的类名/函数
  1384. * @returns {*}
  1385. */
  1386. removeClass: function(name){
  1387. return this.each(function(idx){
  1388. if (!('className' in this)) return
  1389. if (name === undefined) return className(this, '')
  1390. classList = className(this)
  1391. funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
  1392. //替换删除
  1393. classList = classList.replace(classRE(klass), " ")
  1394. })
  1395. className(this, classList.trim())
  1396. })
  1397. },
  1398.  
  1399. /**
  1400. *切换类的添加或移除
  1401. * 原理 如果存在,即removeClass移除,不存在,即addClass添加
  1402. * @param name 类名/空格分隔的类名/函数
  1403. * @param when
  1404. * @returns {*}
  1405. */
  1406. toggleClass: function(name, when){
  1407. if (!name) return this
  1408. return this.each(function(idx){
  1409. var $this = $(this), names = funcArg(this, name, idx, className(this))
  1410. names.split(/\s+/g).forEach(function(klass){
  1411. (when === undefined ? !$this.hasClass(klass) : when) ?
  1412. $this.addClass(klass) : $this.removeClass(klass)
  1413. })
  1414. })
  1415. },
  1416. /**
  1417. * 读写元素 滚动条的垂直偏移
  1418. * 读: 第一个元素 scrollTop 或 pageYOffset
  1419. * 写:所有元素 scrollTop
  1420. * 如果设置的偏移值,滚动做不到,可能不生效,不会取滚动最大值
  1421. * @param value
  1422. * @returns {*}
  1423. */
  1424. scrollTop: function(value){
  1425. if (!this.length) return
  1426. var hasScrollTop = 'scrollTop' in this[]
  1427. //读
  1428. if (value === undefined) return hasScrollTop ? this[].scrollTop : this[].pageYOffset//取scrollTop 或 pageYOffset(Sarifri老版只有它)
  1429.  
  1430. //写
  1431. return this.each(hasScrollTop ?
  1432. function(){ this.scrollTop = value } : //支持scrollTop,直接赋值
  1433. function(){ this.scrollTo(this.scrollX, value) }) //滚到指定坐标
  1434. },
  1435. /**
  1436. * 读写元素 滚动条的垂直偏移
  1437. * 读: 第一个元素 scrollLeft 或 pageXOffset
  1438. * 写:所有元素 scrollLeft
  1439. * @param value
  1440. * @returns {*}
  1441. */
  1442. scrollLeft: function(value){
  1443. if (!this.length) return
  1444. var hasScrollLeft = 'scrollLeft' in this[]
  1445. if (value === undefined) return hasScrollLeft ? this[].scrollLeft : this[].pageXOffset
  1446. return this.each(hasScrollLeft ?
  1447. function(){ this.scrollLeft = value } :
  1448. function(){ this.scrollTo(value, this.scrollY) })
  1449. },
  1450.  
  1451. /**
  1452. * 获取相对父元素的坐标 当前元素的外边框magin到最近父元素内边框的距离
  1453. * @returns {{top: number, left: number}}
  1454. */
  1455. position: function() {
  1456. if (!this.length) return
  1457.  
  1458. var elem = this[],
  1459. // Get *real* offsetParent
  1460. //读到父元素
  1461. offsetParent = this.offsetParent(),
  1462. // Get correct offsets
  1463. //读到坐标
  1464. offset = this.offset(),
  1465. //读到父元素的坐标
  1466. parentOffset = rootNodeRE.test(offsetParent[].nodeName) ? { top: , left: } : offsetParent.offset()
  1467.  
  1468. // Subtract element margins
  1469. // note: when an element has margin: auto the offsetLeft and marginLeft
  1470. // are the same in Safari causing offset.left to incorrectly be 0
  1471. //坐标减去外边框
  1472. offset.top -= parseFloat( $(elem).css('margin-top') ) ||
  1473. offset.left -= parseFloat( $(elem).css('margin-left') ) ||
  1474.  
  1475. // Add offsetParent borders
  1476. //加上父元素的border
  1477. parentOffset.top += parseFloat( $(offsetParent[]).css('border-top-width') ) ||
  1478. parentOffset.left += parseFloat( $(offsetParent[]).css('border-left-width') ) ||
  1479.  
  1480. // Subtract the two offsets
  1481. return {
  1482. top: offset.top - parentOffset.top,
  1483. left: offset.left - parentOffset.left
  1484. }
  1485. },
  1486. /**
  1487. * 返回第一个匹配元素用于定位的祖先元素
  1488. * 原理:读取父元素中第一个其position设为relative或absolute的可见元素
  1489. * @returns {*|HTMLElement}
  1490. */
  1491. offsetParent: function() {
  1492. //map遍历$集,在回调函数里读出最近的定位祖先元素 ,再返回包含这些定位元素的$对象
  1493. return this.map(function(){
  1494. //读取定位父元素,没有,则body
  1495. var parent = this.offsetParent || document.body
  1496.  
  1497. //如果找到的定位元素 position=‘static’继续往上找,直到body/Html
  1498. while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
  1499. parent = parent.offsetParent
  1500. return parent
  1501. })
  1502. }
  1503. }
  1504.  
  1505. // for now
  1506. $.fn.detach = $.fn.remove
  1507.  
  1508. // Generate the `width` and `height` functions
  1509. /*
  1510. * width height 模板方法 读写width/height
  1511. */
  1512. ;['width', 'height'].forEach(function(dimension){
  1513. //将width,hegiht转成Width,Height,用于document获取
  1514. var dimensionProperty =
  1515. dimension.replace(/./, function(m){ return m[].toUpperCase() })
  1516.  
  1517. $.fn[dimension] = function(value){
  1518. var offset, el = this[]
  1519. //读时,是window 用innerWidth,innerHeight获取
  1520. if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
  1521. //是document,用scrollWidth,scrollHeight获取
  1522. isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
  1523. (offset = this.offset()) && offset[dimension] //TODO:否则用 offsetWidth offsetHeight
  1524.  
  1525. //写
  1526. else return this.each(function(idx){
  1527. el = $(this)
  1528. //设值,支持value为函数
  1529. el.css(dimension, funcArg(this, value, idx, el[dimension]()))
  1530. })
  1531. }
  1532. })
  1533.  
  1534. function traverseNode(node, fun) {
  1535. fun(node)
  1536. for (var i = , len = node.childNodes.length; i < len; i++)
  1537. traverseNode(node.childNodes[i], fun)
  1538. }
  1539.  
  1540. // Generate the `after`, `prepend`, `before`, `append`,
  1541. // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
  1542. /**
  1543. * TODO: 模板方法:DOM的插入操作
  1544. */
  1545. adjacencyOperators.forEach(function(operator, operatorIndex) {
  1546. var inside = operatorIndex % //=> prepend, append 有余数 注意forEach遍历出的索引从0开始
  1547.  
  1548. $.fn[operator] = function(){
  1549. // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
  1550. //nodes HTML字符串生成的DOM集
  1551. var argType, nodes = $.map(arguments, function(arg) {
  1552. argType = type(arg)
  1553. //传参非 object、array、null,就直接调用zepto.fragment生成DOM
  1554. return argType == "object" || argType == "array" || arg == null ?
  1555. arg : zepto.fragment(arg)
  1556. }),
  1557. //如果$长度>1,需要克隆里面的元素
  1558. parent, copyByClone = this.length >
  1559.  
  1560. if (nodes.length < ) return this //为0,不需要操作,直接返回
  1561.  
  1562. //遍历源$,执行插入 _指代此参数无效或不用
  1563. return this.each(function(_, target){
  1564. parent = inside ? target : target.parentNode //prepend, append取父元素
  1565.  
  1566. // convert all methods to a "before" operation
  1567.  
  1568. //用insertBefore模拟实现
  1569. target = operatorIndex == ? target.nextSibling : //after,target等于下一个兄弟元素,然后将DOM通过insertBefore插入到target前
  1570. operatorIndex == ? target.firstChild : //prepend target为parent的第一个元素,然后将DOM通过insertBefore插入到target前
  1571. operatorIndex == ? target : // before 直接将将DOM通过insertBefore插入到target前
  1572. null // append 直接调用$(target).append
  1573.  
  1574. //父元素是否在document中
  1575. var parentInDocument = $.contains(document.documentElement, parent)
  1576.  
  1577. //遍历待插入的元素
  1578. nodes.forEach(function(node){
  1579. //克隆
  1580. if (copyByClone) node = node.cloneNode(true)
  1581.  
  1582. //定位元素不存在,,没法执行插入操作,直接删除,返回
  1583. else if (!parent) return $(node).remove()
  1584.  
  1585. //插入节点后,如果被插入的节点是SCRIPT,则执行里面的内容并将window设为上下文
  1586. //插入元素
  1587. parent.insertBefore(node, target)
  1588.  
  1589. //如果父元素在document里,修正script标签。原因是script标签通过innerHTML加入DOM不执行。需要在全局环境下执行它
  1590. if (parentInDocument) traverseNode(node, function(el){
  1591. if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
  1592. (!el.type || el.type === 'text/javascript') && !el.src)
  1593. window['eval'].call(window, el.innerHTML)
  1594. })
  1595. })
  1596. })
  1597. }
  1598.  
  1599. // after => insertAfter
  1600. // prepend => prependTo
  1601. // before => insertBefore
  1602. // append => appendTo
  1603. /**
  1604. * 插入方法转换
  1605. * @param html
  1606. * @returns {*}
  1607. */
  1608. $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
  1609. $(html)[operator](this)
  1610. return this
  1611. }
  1612. })
  1613.  
  1614. // zepto.Z.prototype 继承所有$.fn所有原型方法
  1615. zepto.Z.prototype = Z.prototype = $.fn
  1616.  
  1617. // Export internal API functions in the `$.zepto` namespace
  1618. zepto.uniq = uniq
  1619. zepto.deserializeValue = deserializeValue
  1620. $.zepto = zepto
  1621.  
  1622. return $
  1623. })()
  1624.  
  1625. // If `$` is not yet defined, point it to `Zepto`
  1626. window.Zepto = Zepto
  1627. window.$ === undefined && (window.$ = Zepto)

构造Zepto对象

  结构

  1. var Zepto = (function() {
  2.  
  3. //实际构造函数`
  4. function Z(dom, selector) {
  5. var i, len = dom ? dom.length :
  6. for (i = ; i < len; i++) this[i] = dom[i]
  7. this.length = len
  8. this.selector = selector || ''
  9. }
  10.  
  11. zepto.Z = function(dom, selector) {
  12. return new Z(dom, selector)
  13. }
  14.  
  15. //是否Zepto对象
  16. zepto.isZ = function(object) {
  17. return object instanceof zepto.Z
  18. }
  19.  
  20. // 初始化参数、DOM
  21. zepto.init = function(selector, context) {
  22. ...
  23. return zepto.Z(dom, selector)
  24. }
  25.  
  26. //构造函数
  27. $ = function(selector, context){
  28. return zepto.init(selector, context)
  29. }
  30. //原型设置
  31. $.fn = { ... }
  32.  
  33. zepto.Z.prototype = Z.prototype = $.fn
  34.  
  35. $.zepto = zepto
  36.  
  37. return $
  38. })()
  39.  
  40. // If `$` is not yet defined, point it to `Zepto`
  41. window.Zepto = Zepto
  42. window.$ === undefined && (window.$ = Zepto)

  主要方法图

   

属性操作

  

DOM遍历

  

  

DOM操作

  

样式操作

  

 

 

Zepto源码分析-zepto模块的更多相关文章

  1. zepto源码分析·core模块

    准备说明 该模块定义了库的原型链结构,生成了Zepto变量,并将其以'Zepto'和'$'的名字注册到了window,然后开始了其它模块的拓展实现. 模块内部除了对选择器和zepto对象的实现,就是一 ...

  2. Zepto源码分析-event模块

    源码注释 // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT l ...

  3. Zepto源码分析-ajax模块

    源码注释 // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT l ...

  4. Zepto源码分析-form模块

    源码注释 // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT l ...

  5. zepto源码分析·ajax模块

    准备知识 在看ajax实现的时候,如果对ajax技术知识不是很懂的话,可以参看下ajax基础,以便读分析时不会那么迷糊 全局ajax事件 默认$.ajaxSettings设置中的global为true ...

  6. zepto源码分析·event模块

    准备知识 事件的本质就是发布/订阅模式,dom事件也不例外:先简单说明下发布/订阅模式,dom事件api和兼容性 发布/订阅模式 所谓发布/订阅模式,用一个形象的比喻就是买房的人订阅楼房消息,售楼处发 ...

  7. Zepto源码分析-deferred模块

    源码注释 // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT l ...

  8. Zepto源码分析-callbacks模块

    // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT licens ...

  9. zepto源码分析系列

    如果你也开发移动端web,如果你也用zepto,应该值得你看看.有问题请留言. Zepto源码分析-架构 Zepto源码分析-zepto(DOM)模块 Zepto源码分析-callbacks模块 Ze ...

随机推荐

  1. 设计模式的征途—3.工厂方法(Factory Method)模式

    上一篇的简单工厂模式虽然简单,但是存在一个很严重的问题:当系统中需要引入新产品时,由于静态工厂方法通过所传入参数的不同来创建不同的产品,这必定要修改工厂类的源代码,将违背开闭原则.如何实现新增新产品而 ...

  2. JAVA----类的继承1(extends)

    要学习类的继承,首先应当理解继承的含义: 来自新华词典的释义: ①依法承受(死者的遗产等):-权ㄧ-人. ②泛指把前人的作风.文化.知识等接受过来:-优良传统ㄧ-文化遗产. ③后人继续做前人遗留下来的 ...

  3. python安装win32api pywin32 后出现 ImportError: DLL load failed

    ImportError: DLL load failed: \xd5\xd2\xb2\xbb\xb5\xbd\xd6\xb8\xb6\xa8\xb5\xc4\xc4\xa3\xbf\xe9\xa1\x ...

  4. Python 一行代码

    Python语法十分便捷,通过几个简单例子了解其趣味 1.Fizz.Buzz问题为: 打印数字1到100, 3的倍数打印"Fizz", 5的倍数打印"Buzz" ...

  5. 跨语言学习的基本思路及python的基础学习

    笔者是C#出身,大学四年主修C#,工作三年也是C#语言开发.但在学校里其他的语言也有相应的课程,eg:Java,Php,C++都学过,当然只是学了皮毛(大学嘛,你懂得),严格来说未必入门,但这些语言的 ...

  6. JavaScript中screen对象的两个属性

    Screen 对象 Screen 对象包含有关客户端显示屏幕的信息. 这里说一下今天用到的两个属性:availHeigth,availWidth avaiHeigth返回显示屏幕的高度 (除 Wind ...

  7. 【NIO】Java NIO之选择器

    一.前言 前面已经学习了缓冲和通道,接着学习选择器. 二.选择器 2.1 选择器基础 选择器管理一个被注册的通道集合的信息和它们的就绪状态,通道和选择器一起被注册,并且选择器可更新通道的就绪状态,也可 ...

  8. Linux Shell——函数的使用

    文/一介书生,一枚码农. scripts are for lazy people. 函数是存在内存里的一组代码的命名的元素.函数创建于脚本运行环境之中,并且可以执行. 函数的语法结构为: functi ...

  9. Tomcat 热部署

    Tomcat热部署就是实现不停机的发布项目和更新项目 1.修改conf目录下的tomcat-users.xml文件 在<tomcat-user>添加如下配置 [root@localhost ...

  10. 学习sql基础注入的方法

    作为一个初学者的我,经学习发现基础真的十分重要, 这个随笔是写给我自己的希望我能坚持住 当然,我也希望对其他人有点帮助 在sql注入的过程中,我越发感觉那些基础函数的重要性 其实我感觉sql注入其实就 ...