Zepto源码分析-zepto模块
生活随笔
收集整理的這篇文章主要介紹了
Zepto源码分析-zepto模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
源碼
// Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license.var Zepto = (function() {//定義局部變量 concat = emptyArray.concat 縮短作用域鏈var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,document = window.document,//緩存元素的默認display屬性elementDisplay = {},//緩存匹配class正則表達式 ,hasClass判斷用到,classCache = {},//設置CSS時,不用加px單位的屬性cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },//匹配HTML代碼fragmentRE = /^\s*<(\w+|!)[^>]*>/,//TODO 匹配單個HTML標簽singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,//TODO 匹配自閉合標簽tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//匹配根節點rootNodeRE = /^(?:body|html)$/i,//匹配A-ZcapitalRE = /([A-Z])/g,// special attributes that should be get/set via method calls//需要提供get和set的方法名methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],//相鄰DOM的操作adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],table = document.createElement('table'),tableRow = document.createElement('tr'),//這里的用途是當需要給tr,tbody,thead,tfoot,td,th設置innerHTMl的時候,需要用其父元素作為容器來裝載HTML字符串containers = {'tr': document.createElement('tbody'),'tbody': table, 'thead': table, 'tfoot': table,'td': tableRow, 'th': tableRow,'*': document.createElement('div')},//當DOM ready的時候,document會有以下三種狀態的一種readyRE = /complete|loaded|interactive/,simpleSelectorRE = /^[\w-]*$/,//緩存對象類型,用于類型判斷 如objectclass2type = {},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'},isArray = Array.isArray ||function(object){ return object instanceof Array }/*** 元素是否匹配選擇器* @param element* @param selector* @returns {*}*/zepto.matches = function(element, selector) {//沒參數,非元素,直接返回if (!selector || !element || element.nodeType !== 1) return false//如果瀏覽器支持MatchesSelector 直接調用var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||element.oMatchesSelector || element.matchesSelectorif (matchesSelector) return matchesSelector.call(element, selector)//瀏覽器不支持MatchesSelectorvar match, parent = element.parentNode, temp = !parent//元素沒有父元素,存入到臨時的div tempParentif (temp) (parent = tempParent).appendChild(element)//再通過父元素來搜索此表達式。 找不到-1 找到有索引從0開始//注意 ~取反位運算符 作用是將值取負數再減1 如-1變成0 0變成-1match = ~zepto.qsa(parent, selector).indexOf(element)//清理臨時父節點temp && tempParent.removeChild(element)//返回匹配return match}/*** 獲取對象類型* @param obj* @returns {*}*/function type(obj) {return obj == null ? String(obj) :class2type[toString.call(obj)] || "object"}function isFunction(value) { return type(value) == "function" }function isWindow(obj) { return obj != null && obj == obj.window }function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }function isObject(obj) {return type(obj) == "object"}/*** 是否是純粹對象 JSON/new Object* @param obj* @returns {*|boolean|boolean}*/function isPlainObject(obj) {//是對象 非window 非new時需要傳參的return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype}/*** 偽數組/數組判斷* @param obj* @returns {boolean}*/function likeArray(obj) { return typeof obj.length == 'number' }/*** 清掉數組中的null/undefined* @param array* @returns {*}*/function compact(array) { return filter.call(array, function(item){ return item != null }) }/*** 返回一個數組副本* 利用空數組$.fn.concat.apply([], array) 合并新的數組,返回副本* @param array* @returns {*|Function|Function|Function|Function|Function|Zepto.fn.concat|Zepto.fn.concat|Zepto.fn.concat|Array|string}*/function flatten(array) {return array.length > 0 ? $.fn.concat.apply([], array) : array}/*** 將'-'字符串轉成駝峰格式* @param str* @returns {*|void}*/camelize = function(str){return str.replace(/-+(.)?/g, function(match, chr){//匹配到-字符后的字母,轉換為大寫返回return chr ? chr.toUpperCase() : ''})}/*** 字符串轉換成瀏覽器可識別的 -拼接形式。 如background-color** @param str* @returns {string}*/function dasherize(str) {return str.replace(/::/g, '/') //將::替換成/.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') //在大小寫字符之間插入_,大寫在前,比如AAAbb,得到AA_Abb.replace(/([a-z\d])([A-Z])/g, '$1_$2') //在大小寫字符之間插入_,小寫或數字在前,比如bbbAaa,得到bbb_Aaa.replace(/_/g, '-') //將_替換成-.toLowerCase() //轉成小寫 }//數組去重,如果該條數據在數組中的位置與循環的索引值不相同,則說明數組中有與其相同的值uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }/*** 將參數變為正則表達式* @param name* @returns {*}*/function classRE(name) {//classCache,緩存正則//TODO 緩存可以理解,但應該在重復使用第二次時再緩存吧,直接緩存?return name in classCache ?classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))}/*** 除了cssNumber指定的不需要加單位的,默認加上px* @param name* @param value* @returns {string}*/function maybeAddPx(name, value) {return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value}/*** 獲取元素的默認display屬性* 是為了兼容什么?* @param nodeName* @returns {*}*/function defaultDisplay(nodeName) {var element, displayif (!elementDisplay[nodeName]) { //緩存里沒有 element = document.createElement(nodeName)document.body.appendChild(element)display = getComputedStyle(element, '').getPropertyValue("display")element.parentNode.removeChild(element)// display == "none",設置成blaock,即隱藏-顯示display == "none" && (display = "block")elementDisplay[nodeName] = display //TODO:緩存元素的默認display屬性,緩存干嘛? }return elementDisplay[nodeName]}/*** 獲取元素的子節集* 原理:原生方法children 老的火狐不支持的,遍歷childNodes* @param element* @returns {*}*/function children(element) {return 'children' in element ?slice.call(element.children) :$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })}/*** 構造器* @param dom* @param selector* @constructor*/function Z(dom, selector) {var i, len = dom ? dom.length : 0for (i = 0; i < len; i++) this[i] = dom[i]this.length = lenthis.selector = selector || ''}// `$.zepto.fragment` takes a html string and an optional tag name// to generate DOM nodes nodes from the given html string.// The generated DOM nodes are returned as an array.// This function can be overriden in plugins for example to make// it compatible with browsers that don't support the DOM fully./*** 內部函數 HTML 轉換成 DOM* 原理是 創建父元素,innerHTML轉換* @param html html片段* @param name 容器標簽名* @param propertie 附加的屬性對象* @returns {*}*/zepto.fragment = function(html, name, properties) {var dom, nodes, container// A special case optimization for a single tag//如果是單個元素,創建dom//TODO// RegExp 是javascript中的一個內置對象。為正則表達式。 // RegExp.$1是RegExp的一個屬性,指的是與正則表達式匹配的第一個 子匹配(以括號為標志)字符串,以此類推,RegExp.$2,RegExp.$3,..RegExp.$99總共可以有99個匹配if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))if (!dom) {//修正自閉合標簽 如<div />,轉換成<div></div>if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")//給name取元素名if (name === undefined) name = fragmentRE.test(html) && RegExp.$1//設置容器名,如果不是tr,tbody,thead,tfoot,td,th,則容器名為div//為什么設置容器,是嚴格按照HTML語法,雖然tr td th瀏覽器會會自動添加tbodyif (!(name in containers)) name = '*'container = containers[name] //創建容器container.innerHTML = '' + html //生成DOM//取容器的子節點,TODO:子節點集會返回dom = $.each(slice.call(container.childNodes), function(){container.removeChild(this) //把創建的子節點逐個刪除 })}//如果properties是對象,遍歷它,將它設置成DOM的屬性if (isPlainObject(properties)) {//轉換成Zepto Obj,方便調用Zepto的方法nodes = $(dom)//遍歷對象,設置屬性 $.each(properties, function(key, value) {//優先獲取屬性修正對象,通過修正對象讀寫值// methodAttributes包含'val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset',//TODO: 奇怪的屬性if (methodAttributes.indexOf(key) > -1) nodes[key](value)else nodes.attr(key, value)})}//返回dom數組 如[div,div]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 overriden in plugins.//入口函數?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 overriden in plugins.//判斷給定的參數是否是Zepto集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 overriden in plugins.zepto.init = function(selector, context) {var dom// If nothing given, return an empty Zepto collection//未傳參,undefined進行boolean轉換,返回空Zepto對象if (!selector) return zepto.Z()// Optimize for string selectors//selector是字符串,即css表達式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 <//如果是<開頭 >結尾 基本的HTML代碼時if (selector[0] == '<' && fragmentRE.test(selector))//調用片段生成domdom = 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//如果傳遞了上下文,在上下文中查找元素else if (context !== undefined) return $(context).find(selector)// If it's a CSS selector, use it to select nodes.//通過css表達式查找元素else dom = zepto.qsa(document, selector)}// If a function is given, call it when the DOM is ready//如果selector是函數,則在DOM ready的時候執行它else if (isFunction(selector)) return $(document).ready(selector)// If a Zepto collection is given, just return it//如果selector是一個Zepto對象,返回它自己else if (zepto.isZ(selector)) return selectorelse {// normalize array if an array of nodes is given//如果selector是數組,過濾null,undefinedif (isArray(selector)) dom = compact(selector)// Wrap DOM nodes.//如果selector是對象,TODO://轉換為數組? 它應是DOM; 注意DOM節點的typeof值也是object,所以在里面還要再進行一次判斷else if (isObject(selector))dom = [selector], selector = null// If it's a html fragment, create nodes from it//如果selector是復雜的HTML代碼,調用片段換成DOM節點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//如果存在上下文context,仍在上下文中查找selectorelse if (context !== undefined) return $(context).find(selector)// And last but no least, if it's a CSS selector, use it to select nodes.//如果沒有給定上下文,在document中查找selectorelse 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.$ = function(selector, context){return zepto.init(selector, context)}/*** 內部方法:用戶合并一個或多個對象到第一個對象* @param target 目標對象 對象都合并到target里* @param source 合并對象* @param deep 是否執行深度合并*/function extend(target, source, deep) {for (key in source)//如果深度合并if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {//如果要合并的屬性是對象,但target對應的key非對象if (isPlainObject(source[key]) && !isPlainObject(target[key]))target[key] = {}//如果要合并的屬性是數組,但target對應的key非數組if (isArray(source[key]) && !isArray(target[key]))target[key] = []//執行遞歸合并 extend(target[key], source[key], deep)}//不是深度合并,直接覆蓋//TODO: 合并不顯得太簡單了?else if (source[key] !== undefined) target[key] = source[key]}// Copy all but undefined properties from one or more// objects to the `target` object./*** 對外方法* 合并* @param target* @returns {*}*/$.extend = function(target){var deep, //是否執行深度合并args = slice.call(arguments, 1)//arguments[0]是target,被合并對象,或為deepif (typeof target == 'boolean') {//第一個參數為boolean值時,表示是否深度合并deep = targettarget = args.shift() //target取第二個參數 }//遍歷后面的參數,都合并到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 overriden in plugins./*** 通過選擇器表達式查找DOM* 原理 判斷下選擇器的類型(id/class/標簽/表達式)* 使用對應方法getElementById getElementsByClassName getElementsByTagName querySelectorAll 查找* @param element* @param selector* @returns {Array}*/zepto.qsa = function(element, selector){var found,maybeID = selector[0] == '#',//ID標識maybeClass = !maybeID && selector[0] == '.',//class 標識//是id/class,就取'#/.'后的字符串,如‘#test’取‘test'nameOnly = maybeID || maybeClass ? selector.slice(1) : selector,isSimple = simpleSelectorRE.test(nameOnly) //TODO:是否為單個選擇器 沒有空格return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById//通過getElementById查找DOM,找到返回[dom],找不到返回[]( (found = element.getElementById(nameOnly)) ? [found] : [] ) ://當element不為元素節點或document fragment時,返回空//元素element 1 屬性attr 2 文本text 3 注釋comments 8 文檔document 9 片段 fragment 11(element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :slice.call(//如果是class,通過getElementsByClassName查找DOM,isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagNamemaybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a classelement.getElementsByTagName(selector) : // Or a tag //如果是標簽名,調用getElementsByTagName//最后調用querySelectorAllelement.querySelectorAll(selector) // Or it's not simple, and we need to query all )}/*** 在元素集中過濾某些元素* @param nodes* @param selector* @returns {*|HTMLElement}*/function filtered(nodes, selector) {return selector == null ? $(nodes) : $(nodes).filter(selector)}/*** 父元素是否包含子元素* @type {Function}*/$.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 truereturn false}/*** 處理 arg為函數/值* 為函數,返回函數返回值* 為值,返回值* @param context* @param arg* @param idx* @param payload* @returns {*}*/function funcArg(context, arg, idx, payload) {return isFunction(arg) ? arg.call(context, idx, payload) : arg}/*** 設置屬性* @param node* @param name* @param value*/function setAttribute(node, name, value) {//value為null/undefined,處理成刪除,否則設值value == null ? node.removeAttribute(name) : node.setAttribute(name, value)}// access className property while respecting SVGAnimatedString/*** 對SVGAnimatedString的兼容?* @param node* @param value* @returns {*}*/function className(node, value){var klass = node.className || '',svg = klass && klass.baseVal !== undefinedif (value === undefined) return svg ? klass.baseVal : klasssvg ? (klass.baseVal = value) : (node.className = value) //class設值 }// "true" => true// "false" => false// "null" => null// "42" => 42// "42.5" => 42.5// "08" => "08"// JSON => parse if valid// String => self/*** 序列化值 把自定義數據讀出來時做應該的轉換,$.data()方法使用* @param value* @returns {*}*/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/*** 空對象* @param obj* @returns {boolean}*/$.isEmptyObject = function(obj) {var namefor (name in obj) return falsereturn true}/*** 獲取在數組中的索引* @param elem* @param array* @param i* @returns {number}*/$.inArray = function(elem, array, i){//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() {}/*** 內部方法* 遍歷對象/數組 在每個元素上執行回調,將回調的返回值放入一個新的數組返回* @param elements* @param callback* @returns {*}*/$.map = function(elements, callback){var value, values = [], i, key//如果被遍歷的數據是數組或者Zepto(偽數組)if (likeArray(elements))for (i = 0; i < elements.length; i++) {value = callback(elements[i], i)if (value != null) values.push(value)}else//如果是對象for (key in elements) {value = callback(elements[key], key)if (value != null) values.push(value)}return flatten(values)}/*** 以集合每一個元素作為上下文,來執行回調函數* @param elements* @param callback* @returns {*}*/$.each = function(elements, callback){var i, keyif (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}/*** 查找數組滿足過濾函數的元素* @param elements* @param callback* @returns {*}*/$.grep = function(elements, callback){return filter.call(elements, callback)}if (window.JSON) $.parseJSON = JSON.parse//填充class2type的值$.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//針對DOM的一些操作$.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,/*** 合并多個數組* @returns {*}*/concat: function(){var i, value, args = []for (i = 0; i < arguments.length; i++) {value = arguments[i]args[i] = zepto.isZ(value) ? value.toArray() : value}return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)},// `map` and `slice` in the jQuery API work differently// from their array counterparts/*** 遍歷對象/數組 在每個元素上執行回調,將回調的返回值放入一個新的Zepto返回* @param fn* @returns {*|HTMLElement}*/map: function(fn){return $($.map(this, function(el, i){ return fn.call(el, i, el) }))},/*** slice包裝成Zepto* @returns {*|HTMLElement}*/slice: function(){return $(slice.apply(this, arguments))},/*** 當DOM載入就緒時,綁定回調* 如 $(function(){}) $(document).ready(function(){// 在這里寫你的代碼* @param callback* @returns {*}*/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//如果已經readyif (readyRE.test(document.readyState) && document.body) callback($)//監聽DOM已渲染完畢事件else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)return this},/*** 取Zepto中指定索引的值* @param idx 可選,不傳時,將Zetpo轉換成數組* @returns {*}*/get: function(idx){return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]},/*** 將Zepto(偽數組)轉換成數組* 原理是 偽數組轉換成數組oa = {0:'a',length:1};Array.prototype.slice.call(oa);* 數組轉換偽數組 var obj = {}, push = Array.prototype.push; push.apply(obj,[1,2]);* @returns {*}*/toArray: function(){return this.get()},//獲取集合長度 size: function(){return this.length},/*** 刪除元素集* 原理 parentNode.removeChild* @returns {*}*/remove: function(){//遍歷到其父元素 removeChildreturn this.each(function(){if (this.parentNode != null)this.parentNode.removeChild(this)})},//遍歷集合,將集合中的每一項放入callback中進行處理,去掉結果為false的項,注意這里的callback如果明確返回false//那么就會停止循環了/*** 遍歷Zepto,在每個元素上執行回調函數* @param callback* @returns {*}*/each: function(callback){emptyArray.every.call(this, function(el, idx){//el:元素,idx:下標 傳遞給callback(idx,el)return callback.call(el, idx, el) !== false})return this},/*** 過濾,返回處理結果為true的記錄* @param selector* @returns {*}*/filter: function(selector){//this.not(selector)取到需要排除的集合,第二次再取反(這個時候this.not的參數就是一個集合了),得到想要的集合if (isFunction(selector)) return this.not(this.not(selector))//filter收集返回結果為true的記錄return $(filter.call(this, function(element){//當element與selector匹配,則收集return zepto.matches(element, selector)}))},//將由selector獲取到的結果追加到當前集合中 add: function(selector,context){//追加并去重return $(uniq(this.concat($(selector,context))))},//返回集合中的第1條記錄是否與selector匹配is: function(selector){return this.length > 0 && zepto.matches(this[0], selector)},//排除集合里滿足條件的記錄,接收參數為:css選擇器,function, dom ,nodeList not: function(selector){var nodes=[]//當selector為函數時,safari下的typeof odeList也是function,所以這里需要再加一個判斷selector.call !== undefinedif (isFunction(selector) && selector.call !== undefined)this.each(function(idx){//注意這里收集的是selector.call(this,idx)返回結果為false的時候記錄if (!selector.call(this,idx)) nodes.push(this)})else {//當selector為字符串的時候,對集合進行篩選,也就是篩選出集合中滿足selector的記錄var excludes = typeof selector == 'string' ? this.filter(selector) ://當selector為nodeList時執行slice.call(selector),注意這里的isFunction(selector.item)是為了排除selector為數組的情況//當selector為css選擇器,執行$(selector)(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)this.forEach(function(el){//篩選出不在excludes集合里的記錄,達到排除的目的if (excludes.indexOf(el) < 0) nodes.push(el)})}return $(nodes)//由于上面得到的結果是數組,這里需要轉成zepto對象,以便繼承其它方法,實現鏈寫 },/*接收node和string作為參數,給當前集合篩選出包含selector的集合isObject(selector)是判斷參數是否是node,因為typeof node == 'object'當參數為node時,只需要判讀當前記當里是否包含node節點即可當參數為string時,則在當前記錄里查詢selector,如果長度為0,則為false,filter函數就會過濾掉這條記錄,否則保存該記錄*/has: function(selector){return this.filter(function(){return isObject(selector) ?$.contains(this, selector) :$(this).find(selector).size()})},/*** 取Zepto中的指定索引的元素,再包裝成Zepto返回* @param idx* @returns {*}*/eq: function(idx){return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)},/*取第一條$(元素)*/first: function(){var el = this[0] //取第一個元素//非$對象,轉換成$,//如果element,isObject會判斷為true。zepto也判斷為true,都會重新轉換成$(el)//TODO:這里是bug?return el && !isObject(el) ? el : $(el)},/*取最后一條$(元素)*/last: function(){var el = this[this.length - 1]return el && !isObject(el) ? el : $(el)},/*在當前集合中查找selector,selector可以是集合,選擇器,以及節點*/find: function(selector){var result, $this = this//如果selector為node或者zepto集合時if (!selector) result = $()//遍歷selector,篩選出父級為集合中記錄的selectorelse if (typeof selector == 'object')result = $(selector).filter(function(){var node = this//如果$.contains(parent, node)返回true,則emptyArray.some也會返回true,外層的filter則會收錄該條記錄return emptyArray.some.call($this, function(parent){return $.contains(parent, node)})})//如果selector是css選擇器//如果當前集合長度為1時,調用zepto.qsa,將結果轉成zepto對象else if (this.length == 1) result = $(zepto.qsa(this[0], selector))//如果長度大于1,則調用map遍歷else result = this.map(function(){ return zepto.qsa(this, selector) })return result}, /*** 取最近的滿足selector選擇器的祖先元素* @param selector* @param context* @returns {*|HTMLElement}*/closest: function(selector, context){var node = this[0], collection = falseif (typeof selector == 'object') collection = $(selector)//node遞歸parentNode,直到滿足selector表達式,返回$while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))//當node 不是context,document的時候,取node.parentNodenode = node !== context && !isDocument(node) && node.parentNodereturn $(node)},/*** 取得所有匹配的祖先元素* @param selector* @returns {*}*/parents: function(selector){var ancestors = [], nodes = this//先取得所有祖先元素while (nodes.length > 0) //到不再有父元素時,退出循環//取得所有父元素 //nodes被再賦值為收集到的父元素數組nodes = $.map(nodes, function(node){//獲取父級, isDocument(node) 到Document為止// ancestors.indexOf(node)去重復if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {ancestors.push(node)//收集已經獲取到的父級元素,用于去重復return node}})//篩選出符合selector的祖先元素return filtered(ancestors, selector)},/*** 獲取父元素* @param selector* @returns {*|HTMLElement}*/parent: function(selector){return filtered(uniq(this.pluck('parentNode')), selector)},/*** 獲取子元素集* @param selector* @returns {*|HTMLElement}*/children: function(selector){return filtered(this.map(function(){ return children(this) }), selector)},/*** 獲取iframe的docment,或子節集* @returns {*|HTMLElement}*/contents: function() {return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })},/*** 獲取兄弟節點集* @param selector* @returns {*|HTMLElement}*/siblings: function(selector){return filtered(this.map(function(i, el){//到其父元素取得所有子節點,再排除本身return filter.call(children(el.parentNode), function(child){ return child!==el })}), selector)},/*** 移除所有子元素* 原理: innerHTML = ''* @returns {*}*/empty: function(){return this.each(function(){ this.innerHTML = '' })},/*** 根據是否存在此屬性來獲取當前集合* @param property* @returns {*}*/pluck: function(property){return $.map(this, function(el){ return el[property] })},/*** 展示* @returns {*}*/show: function(){return this.each(function(){//清除內聯樣式display="none"this.style.display == "none" && (this.style.display = '')//計算樣式display為none時,重賦顯示值if (getComputedStyle(this, '').getPropertyValue("display") == "none")this.style.display = defaultDisplay(this.nodeName)//defaultDisplay是獲取元素默認display的方法 })},/*** 替換元素* 原理 before* @param newContent* @returns {*}*/replaceWith: function(newContent){//將要替換內容插到被替換內容前面,然后刪除被替換內容return this.before(newContent).remove()},/*** 匹配的每條元素都被單個元素包裹* @param structure fun/* @returns {*}*/wrap: function(structure){var func = isFunction(structure)if (this[0] && !func) //如果structure是字符串//直接轉成DOMvar dom = $(structure).get(0),//如果DOM已存在(通過在文檔中讀parentNode判斷),或$集不止一條,需要克隆。避免DOM被移動位置clone = dom.parentNode || this.length > 1return this.each(function(index){//遞歸包裹克隆的DOM$(this).wrapAll(func ? structure.call(this, index) :clone ? dom.cloneNode(true) : dom //克隆包裹 )})},/*** 將所有匹配的元素用單個元素包裹起來* @param structure 包裹內容* @returns {*}*/wrapAll: function(structure){if (this[0]) {//包裹內容插入到第一個元素前$(this[0]).before(structure = $(structure))var children// drill down to the inmost element// drill down to the inmost element//取包裹內容里的第一個子元素的最里層while ((children = structure.children()).length) structure = children.first()//將當前$插入到最里層元素里$(structure).append(this)}return this},/*** 包裹到里面 將每一個匹配元素的子內容(包括文本節點)用HTML包裹起來* 原理 獲取節點的內容* @param structure* @returns {*}*/wrapInner: function(structure){var func = isFunction(structure)return this.each(function(index){//遍歷獲取節點的內容,然后用structure將內容包裹var self = $(this), contents = self.contents(),dom = func ? structure.call(this, index) : structurecontents.length ? contents.wrapAll(dom) : self.append(dom) //內容不存在,直接添加structure })},/*** 去包裹 移除元素的父元素* 原理: 子元素替換父元素* @returns {*}*/unwrap: function(){this.parent().each(function(){$(this).replaceWith($(this).children())})return this},/*** 復制元素的副本 TODO:事件、自定義數據會復制嗎?* 原理 cloneNode* @returns {*|HTMLElement}*/clone: function(){return this.map(function(){ return this.cloneNode(true) })},/*** 隱藏* @returns {*}*/hide: function(){return this.css("display", "none")},/*** 不給參數,切換顯示隱藏* 給參數 true show false hide* @param setting* @returns {*}*/toggle: function(setting){return this.each(function(){var el = $(this);(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()})},/*** 篩選前面所有的兄弟元素* @param selector* @returns {*}*/prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },/*** 篩選后面所有的兄弟元素* @param selector* @returns {*}*/next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },/*** 讀寫元素HTML內容* 原理 通過innerHTML讀內容,append()寫內容* @param html* @returns {*|string|string|string|string|string}*/html: function(html){return 0 in arguments ?this.each(function(idx){var originHtml = this.innerHTML //記錄原始的innerHTMl//如果參數html是字符串直接插入到記錄中,//如果是函數,則將當前記錄作為上下文,調用該函數,且傳入該記錄的索引和原始innerHTML作為參數$(this).empty().append( funcArg(this, html, idx, originHtml) )}) :(0 in this ? this[0].innerHTML : null)},/*** 讀寫元素文本內容* 原理: 通過 textContent 讀寫文本* @param text* @returns {*}*/text: function(text){return 0 in arguments ?this.each(function(idx){ //傳參遍歷寫入var newText = funcArg(this, text, idx, this.textContent)this.textContent = newText == null ? '' : ''+newText}) :(0 in this ? this[0].textContent : null) //未傳參讀 },/*** 元素的HTML屬性讀寫* 讀:原理是getAttribute* 寫:原理是setAttribute* @param name* @param value* @returns {undefined}*/attr: function(name, value){var result//僅有name,且為字符串時,表示讀return (typeof name == 'string' && !(1 in arguments)) ?//$是空的 或里面的元素非元素,返回undefined(!this.length || this[0].nodeType !== 1 ? undefined ://直接用getAttribute(name)讀,(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result) : //否則是寫,不管name為對象{k:v},或name value 都存在this.each(function(idx){if (this.nodeType !== 1) return //非元素//如果name為對象,批量設置屬性if (isObject(name)) for (key in name) setAttribute(this, key, name[key])//處理value為函數/null/undefined的情況else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))})},/*** 元素的刪除* @param name 單個值 空格分隔* @returns {*}*/removeAttr: function(name){return this.each(function(){this.nodeType === 1 && name.split(' ').forEach(function(attribute){//不傳value,會直接調用removeAttribute刪除屬性setAttribute(this, attribute)}, this)})},//獲取第一條數據的指定的name屬性或者給每條數據添加自定義屬性,注意和setAttribute的區別/*** 元素的DOM屬性讀寫* 原理:Element[name] 操作* @param name* @param value* @returns {*}*/prop: function(name, value){//優先讀取修正屬性,DOM的兩字母屬性都是駝峰格式name = propMap[name] || name//沒有給定value時,為獲取,給定value則給每一條數據添加,value可以為值也可以是一個返回值的函數return (1 in arguments) ?//有value,遍歷寫入this.each(function(idx){this[name] = funcArg(this, value, idx, this[name])}) ://讀第一個元素(this[0] && this[0][name])},/*** 設置自定義數據* 注意與jQuery的區別,jQuery可以讀寫任何數據類型。這里原理是H5的data-,或直接setAttribute/getAttribute,只能讀寫字符串* @param name* @param value* @returns {*}*/data: function(name, value){var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()var data = (1 in arguments) ?this.attr(attrName, value) :this.attr(attrName)return data !== null ? deserializeValue(data) : undefined},/*** 適合表單元素讀寫* 寫: 寫入每個元素 element.value* 讀: 讀第一個元素* @param value 值/函數* @returns {*}*/val: function(value){return 0 in arguments ?//只有一個參數是寫,this.each(function(idx){this.value = funcArg(this, value, idx, this.value)}) ://如果是讀(this[0] && (this[0].multiple ? //對多選的select的兼容處理,返回一個包含被選中的option的值的數組$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :this[0].value))},/*** 讀/寫坐標 距離文檔document的偏移值* 原理: 讀 getBoundingClientRect視窗坐標-頁面偏移 寫:坐標-父元素坐標* @param coordinates* @returns {*}*/offset: function(coordinates){//寫入坐標if (coordinates) return this.each(function(index){var $this = $(this),//如果coordinates是函數,執行函數,coords = funcArg(this, coordinates, index, $this.offset()),//取父元素坐標parentOffset = $this.offsetParent().offset(),//計算出合理的坐標props = {top: coords.top - parentOffset.top,left: coords.left - parentOffset.left}//修正postin static-relativeif ($this.css('position') == 'static') props['position'] = 'relative'//寫入樣式$this.css(props)})//讀取坐標 取第一個元素的坐標if (!this.length) return null//如果父元素是documentif (!$.contains(document.documentElement, this[0]))return {top: 0, left: 0}//讀取到元素相對于頁面視窗的位置var obj = this[0].getBoundingClientRect()//window.pageYOffset就是類似Math.max(document.documentElement.scrollTop||document.body.scrollTop)return {left: obj.left + window.pageXOffset, //文檔水平滾動偏移top: obj.top + window.pageYOffset, //文檔垂直滾動偏移 pageYOffset和scrollTop的區別是? width: Math.round(obj.width),height: Math.round(obj.height)}},/*** 讀寫樣式 寫:內聯樣式 讀:計算樣式* 原理 讀:elment[style]/getComputedStyle, 寫 this.style.cssText 行內樣式設值* @param property String/Array/Fun* @param value* @returns {*}*/css: function(property, value){//只有一個傳參,讀if (arguments.length < 2) {var computedStyle, element = this[0]if(!element) return//getComputedStyle是一個可以獲取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),只讀//讀到計算樣式computedStyle = getComputedStyle(element, '')//設置樣式if (typeof property == 'string')// 字符串//優先讀行內樣式,再讀計算樣式,行內樣式級別最高? TODO:似乎有bug,如果設置了!important 呢return element.style[camelize(property)] || computedStyle.getPropertyValue(property)else if (isArray(property)) { //數組var props = {}$.each(property, function(_, prop){ //遍歷讀取每一條樣式,存入JSON,返回props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))})return props}}//如果是寫var css = ''if (type(property) == 'string') {if (!value && value !== 0) //null,undefined時,刪掉樣式this.each(function(){//刪除 dasherize是將字符串轉換成css屬性(background-color格式)this.style.removeProperty(dasherize(property))})else//‘-’格式值 + px單位css = dasherize(property) + ":" + maybeAddPx(property, value)} else {for (key in property) //是對象時if (!property[key] && property[key] !== 0)//當property[key]的值為null/undefined,刪除屬性this.each(function(){ this.style.removeProperty(dasherize(key)) })else//‘-’格式值 + px單位css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'}//設值 //TODO: this.style.cssText += 未考慮去重了return this.each(function(){ this.style.cssText += ';' + css })},index: function(element){//這里的$(element)[0]是為了將字符串轉成node,因為this是個包含node的數組//當不指定element時,取集合中第一條記錄在其父節點的位置//this.parent().children().indexOf(this[0])這句很巧妙,和取第一記錄的parent().children().indexOf(this)相同return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])},/*** 是否含有指定的類樣式* @param name* @returns {boolean}*/hasClass: function(name){if (!name) return false//some ES5的新方法 有一個匹配,即返回true 。return emptyArray.some.call(this, function(el){//this是classRE(name)生成的正則return this.test(className(el))}, classRE(name))},/*** 增加一個或多個類名* @param name 類名/空格分隔的類名/函數* @returns {*}*/addClass: function(name){if (!name) return this//遍歷增加return this.each(function(idx){//已存在,返回if (!('className' in this)) returnclassList = []var cls = className(this), newName = funcArg(this, name, idx, cls) //修正類名,處理name是函數,SVG動畫兼容的情況//多個類,空格分隔為數組newName.split(/\s+/g).forEach(function(klass){if (!$(this).hasClass(klass)) classList.push(klass)}, this)//設值classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))})},/***刪除一個或多個類名 同addClass* 原理: className.repalce 替換撒謊年初* @param name 類名/空格分隔的類名/函數* @returns {*}*/removeClass: function(name){return this.each(function(idx){if (!('className' in this)) returnif (name === undefined) return className(this, '')classList = className(this)funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){//替換刪除classList = classList.replace(classRE(klass), " ")})className(this, classList.trim())})},/***切換類的添加或移除* 原理 如果存在,即removeClass移除,不存在,即addClass添加* @param name 類名/空格分隔的類名/函數* @param when* @returns {*}*/toggleClass: function(name, when){if (!name) return thisreturn this.each(function(idx){var $this = $(this), names = funcArg(this, name, idx, className(this))names.split(/\s+/g).forEach(function(klass){(when === undefined ? !$this.hasClass(klass) : when) ?$this.addClass(klass) : $this.removeClass(klass)})})},/*** 讀寫元素 滾動條的垂直偏移* 讀: 第一個元素 scrollTop 或 pageYOffset* 寫:所有元素 scrollTop* 如果設置的偏移值,滾動做不到,可能不生效,不會取滾動最大值* @param value* @returns {*}*/scrollTop: function(value){if (!this.length) returnvar hasScrollTop = 'scrollTop' in this[0]//讀if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset//取scrollTop 或 pageYOffset(Sarifri老版只有它)//寫return this.each(hasScrollTop ?function(){ this.scrollTop = value } : //支持scrollTop,直接賦值function(){ this.scrollTo(this.scrollX, value) }) //滾到指定坐標 },/*** 讀寫元素 滾動條的垂直偏移* 讀: 第一個元素 scrollLeft 或 pageXOffset* 寫:所有元素 scrollLeft* @param value* @returns {*}*/scrollLeft: function(value){if (!this.length) returnvar hasScrollLeft = 'scrollLeft' in this[0]if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffsetreturn this.each(hasScrollLeft ?function(){ this.scrollLeft = value } :function(){ this.scrollTo(value, this.scrollY) })},/*** 獲取相對父元素的坐標 當前元素的外邊框magin到最近父元素內邊框的距離* @returns {{top: number, left: number}}*/position: function() {if (!this.length) returnvar elem = this[0],// Get *real* offsetParent//讀到父元素offsetParent = this.offsetParent(),// Get correct offsets//讀到坐標offset = this.offset(),//讀到父元素的坐標parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()// Subtract element margins// note: when an element has margin: auto the offsetLeft and marginLeft// are the same in Safari causing offset.left to incorrectly be 0//坐標減去外邊框offset.top -= parseFloat( $(elem).css('margin-top') ) || 0offset.left -= parseFloat( $(elem).css('margin-left') ) || 0// Add offsetParent borders//加上父元素的borderparentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0// Subtract the two offsetsreturn {top: offset.top - parentOffset.top,left: offset.left - parentOffset.left}},/*** 返回第一個匹配元素用于定位的祖先元素* 原理:讀取父元素中第一個其position設為relative或absolute的可見元素* @returns {*|HTMLElement}*/offsetParent: function() {//map遍歷$集,在回調函數里讀出最近的定位祖先元素 ,再返回包含這些定位元素的$對象return this.map(function(){//讀取定位父元素,沒有,則bodyvar parent = this.offsetParent || document.body//如果找到的定位元素 position=‘static’繼續往上找,直到body/Htmlwhile (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")parent = parent.offsetParentreturn parent})}}// for now$.fn.detach = $.fn.remove// Generate the `width` and `height` functions/** width height 模板方法 讀寫width/height*/;['width', 'height'].forEach(function(dimension){//將width,hegiht轉成Width,Height,用于document獲取var dimensionProperty =dimension.replace(/./, function(m){ return m[0].toUpperCase() })$.fn[dimension] = function(value){var offset, el = this[0]//讀時,是window 用innerWidth,innerHeight獲取if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] ://是document,用scrollWidth,scrollHeight獲取isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :(offset = this.offset()) && offset[dimension] //TODO:否則用 offsetWidth offsetHeight//寫else return this.each(function(idx){el = $(this)//設值,支持value為函數el.css(dimension, funcArg(this, value, idx, el[dimension]()))})}})function traverseNode(node, fun) {fun(node)for (var i = 0, len = node.childNodes.length; i < len; i++)traverseNode(node.childNodes[i], fun)}// Generate the `after`, `prepend`, `before`, `append`,// `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods./*** TODO: 模板方法:DOM的插入操作*/adjacencyOperators.forEach(function(operator, operatorIndex) {var inside = operatorIndex % 2 //=> prepend, append 有余數 注意forEach遍歷出的索引從0開始 $.fn[operator] = function(){// arguments can be nodes, arrays of nodes, Zepto objects and HTML strings//nodes HTML字符串生成的DOM集var argType, nodes = $.map(arguments, function(arg) {argType = type(arg)//傳參非 object、array、null,就直接調用zepto.fragment生成DOMreturn argType == "object" || argType == "array" || arg == null ?arg : zepto.fragment(arg)}),//如果$長度>1,需要克隆里面的元素parent, copyByClone = this.length > 1if (nodes.length < 1) return this //為0,不需要操作,直接返回//遍歷源$,執行插入 _指代此參數無效或不用return this.each(function(_, target){parent = inside ? target : target.parentNode //prepend, append取父元素// convert all methods to a "before" operation//用insertBefore模擬實現target = operatorIndex == 0 ? target.nextSibling : //after,target等于下一個兄弟元素,然后將DOM通過insertBefore插入到target前operatorIndex == 1 ? target.firstChild : //prepend target為parent的第一個元素,然后將DOM通過insertBefore插入到target前operatorIndex == 2 ? target : // before 直接將將DOM通過insertBefore插入到target前null // append 直接調用$(target).append//父元素是否在document中var parentInDocument = $.contains(document.documentElement, parent)//遍歷待插入的元素 nodes.forEach(function(node){//克隆if (copyByClone) node = node.cloneNode(true)//定位元素不存在,,沒法執行插入操作,直接刪除,返回else if (!parent) return $(node).remove()//插入節點后,如果被插入的節點是SCRIPT,則執行里面的內容并將window設為上下文//插入元素 parent.insertBefore(node, target)//如果父元素在document里,修正script標簽。原因是script標簽通過innerHTML加入DOM不執行。需要在全局環境下執行它if (parentInDocument) traverseNode(node, function(el){if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&(!el.type || el.type === 'text/javascript') && !el.src)window['eval'].call(window, el.innerHTML)})})})}// after => insertAfter// prepend => prependTo// before => insertBefore// append => appendTo/*** 插入方法轉換* @param html* @returns {*}*/$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){$(html)[operator](this)return this}})// zepto.Z.prototype 繼承所有$.fn所有原型方法zepto.Z.prototype = Z.prototype = $.fn// Export internal API functions in the `$.zepto` namespacezepto.uniq = uniqzepto.deserializeValue = deserializeValue$.zepto = zeptoreturn $ })()// If `$` is not yet defined, point it to `Zepto` window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto)?
?
構造Zepto對象
結構
var Zepto = (function() {//實際構造函數` function Z(dom, selector) {var i, len = dom ? dom.length : 0for (i = 0; i < len; i++) this[i] = dom[i]this.length = lenthis.selector = selector || ''}zepto.Z = function(dom, selector) {return new Z(dom, selector)}//是否Zepto對象zepto.isZ = function(object) {return object instanceof zepto.Z}// 初始化參數、DOMzepto.init = function(selector, context) {...return zepto.Z(dom, selector)}//構造函數$ = function(selector, context){return zepto.init(selector, context)}//原型設置$.fn = { ... }zepto.Z.prototype = Z.prototype = $.fn$.zepto = zeptoreturn $ })()// If `$` is not yet defined, point it to `Zepto` window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto)?
主要方法圖
屬性操作
?
DOM遍歷
DOM操作
?
樣式操作
?
?
轉載于:https://www.cnblogs.com/mominger/p/4369206.html
總結
以上是生活随笔為你收集整理的Zepto源码分析-zepto模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]有关IIS的虚拟目录的控制总结
- 下一篇: python3 枚举定义和使用