跟着Zepto學dom(二)

上期中咱們看了元素選擇器、attr和class的源碼,今天咱們來看下其append等的操做是如何進行的。javascript

clone: function(){
  return this.map(function(){ return this.cloneNode(true) })
}複製代碼

this.cloneNode(flag) 其返回this的節點的一個副本flag爲true表示深度克隆,爲了兼容性,該flag最好填寫。css

children: function(selector){
  return filtered(this.map(function(){ return children(this) }), selector)
}
function filtered(nodes, selector) {
//當selector不爲空的時候。
  return selector == null ? $(nodes) : $(nodes).filter(selector)
}
function children(element) {
//爲了兼容性
  return 'children' in element ?
//返回 一個Node的子elements,在IE8中會出現包含註釋節點的狀況,
//但在此處並不會調用該方法。
    slice.call(element.children) :
//不支持children的狀況下
    $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
}
filter: function(selector){
  if (isFunction(selector)) return this.not(this.not(selector))
  return $(filter.call(this, function(element){
    return zepto.matches(element, selector)
  }))
}
//這也是一個重點,下面將重點分拆這個
zepto.matches = function(element, selector) {
  if (!selector || !element || element.nodeType !== 1) return false
  var matchesSelector = element.matches || element.webkitMatchesSelector ||
                        element.mozMatchesSelector || element.oMatchesSelector ||
                        element.matchesSelector
  if (matchesSelector) return matchesSelector.call(element, selector)
  var match, parent = element.parentNode, temp = !parent
  if (temp) (parent = tempParent).appendChild(element)
  match = ~zepto.qsa(parent, selector).indexOf(element)
  temp && tempParent.removeChild(element)
  return match
}複製代碼

children方法中的'children' in element是爲了檢測瀏覽器是否支持children方法,children兼容到IE9
Element.matches(selectorString)若是元素被指定的選擇器字符串選擇,不然該返回true,selectorString爲css選擇器字符串。該方法的兼容性不錯element.matches的兼容性一覽,在移動端中徹底能夠放心使用,固然在一些老版本上就不能夠避免的要添加上一些前綴。如element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector ||element.matchesSelector所示。html

注:其實在IE8中也能夠經過polyfill的形式去實現該方法,以下所示:java

if (!Element.prototype.matches) {
    Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while (--i >= 0 && matches.item(i) !== this) {}
            return i > -1;
        };
}複製代碼

children方法就如上面所示,其實其內部只是調用了幾個不一樣的函數而已。node

closest

closest: function(selector, context){
  var nodes = [], collection = typeof selector == 'object' && $(selector)
  this.each(function(_, node){
//當node存在同時(collection中擁有node元素或者node中匹配到了selector)
    while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
//若是給定了context,則node不能等於該context
//注意只要node===context或者isDocument爲true,那麼node則爲false
      node = node !== context && !isDocument(node) && node.parentNode
    if (node && nodes.indexOf(node) < 0) nodes.push(node)
  })
  return $(nodes)
}
//檢測其是否爲document節點
//DOCUMENT_NODE的更多用法能夠前往https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }複製代碼

after prepend before append

這幾種方法都是先經過調用zepto.fragment該方法統一將content的內容生成dom節點,再進行插入動做。同時須要注意的是傳入的內容能夠爲html字符串,dom節點或者節點組成的數組,以下所示:'web

這是一個dom節點數組

',document.createElement('p'),['

這是一個dom節點瀏覽器

',document.createElement('p')]。

var adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ];
adjacencyOperators.forEach(function(operator, operatorIndex) {
//prepend和append的時候inside爲1
  var inside = operatorIndex % 2
  $.fn[operator] = function(){
    var argType, nodes = $.map(arguments, function(arg) {
          var arr = []
//判斷arg的類型,var arg = document.createElement('span');此時div類型爲object
//var arg = $('div'),此時類型爲array
//var arg = '<div>這是一個div</div>',此時類型爲string
          argType = type(arg)
//傳入爲一個數組時
          if (argType == "array") {
            arg.forEach(function(el) {
              if (el.nodeType !== undefined) return arr.push(el)
              else if ($.zepto.isZ(el)) return arr = arr.concat(el.get())
              arr = arr.concat(zepto.fragment(el))
            })
            return arr
          }
          return argType == "object" || arg == null ?
            arg : zepto.fragment(arg)
        }),
        parent, copyByClone = this.length > 1
    if (nodes.length < 1) return this

    return this.each(function(_, target){
//當爲prepend和append的時候其parent爲target
      parent = inside ? target : target.parentNode
//將全部的動做所有調成before的動做,其只是改變parent和target的不一樣
      target = operatorIndex == 0 ? target.nextSibling :
               operatorIndex == 1 ? target.firstChild :
               operatorIndex == 2 ? target :
               null
//檢測parent是否在document
      var parentInDocument = $.contains(document.documentElement, parent)
      nodes.forEach(function(node){
        if (copyByClone) node = node.cloneNode(true)
        else if (!parent) return $(node).remove()
//parent.insertBefore(node,parent)其在當前節點的某個子節點以前再插入一個子節點
//若是parent爲null則node將被插入到子節點的末尾。若是node已經在DOM樹中,node首先會從DOM樹中移除
        parent.insertBefore(node, target)
//若是父元素在 document 內,則調用 traverseNode 來處理 node 節點及 node 節點的全部子節點。主要是檢測 node 節點或其子節點是否爲 script且沒有src地址。
        if (parentInDocument) traverseNode(node, function(el){
          if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
             (!el.type || el.type === 'text/javascript') && !el.src){
//因爲在iframe中有獨立的window對象
//同時因爲insertBefore插入腳本,並不會執行腳本,因此要經過evel的形式去設置。
            var target = el.ownerDocument ? el.ownerDocument.defaultView : window
            target['eval'].call(target, el.innerHTML)
          }
        })
      })
    })
  }
  //該方法生成了方法名,同時對after、prepend、before、append、insertBefore、insertAfter、prependTo八個方法。其核心都是相似的。
  $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
    $(html)[operator](this)
    return this
  }
})
zepto.fragment = function(html, name, properties) {
  var dom, nodes, container,
  containers = {
    'tr': document.createElement('tbody'),
    'tbody': table, 'thead': table, 'tfoot': table,
    'td': tableRow, 'th': tableRow,
    '*': document.createElement('div')
  },
    singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
    tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig
//若是其只爲一個節點,裏面沒有文本節點和子節點外,相似<p></p>,則dom爲p元素。
  if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
  if (!dom) {
//對html進行修復,若是其爲<p/>則修復爲<p></p>
    if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
//設置標籤的名字。
    if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
    if (!(name in containers)) name = '*'
    container = containers[name]
    container.innerHTML = '' + html
    dom = $.each(slice.call(container.childNodes), function(){
//從DOM中刪除一個節點並返回刪除的節點
      container.removeChild(this)
    })
  }
//檢測屬性是否爲對象,若是爲對象的化,則給元素設置屬性。
  if (isPlainObject(properties)) {
    nodes = $(dom)
    $.each(properties, function(key, value) {
      if (methodAttributes.indexOf(key) > -1) nodes[key](value)
      else nodes.attr(key, value)
    })
  }
  return dom
}複製代碼

css

css: function(property, value){
//爲讀取css樣式時
  if (arguments.length < 2) {
    var element = this[0]
    if (typeof property == 'string') {
      if (!element) return
      return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property)
    } else if (isArray(property)) {
      if (!element) return
      var props = {}
      var computedStyle = getComputedStyle(element, '')
      $.each(property, function(_, prop){
        props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
      })
      return props
    }
  }

  var css = ''
  if (type(property) == 'string') {
    if (!value && value !== 0)
      this.each(function(){ this.style.removeProperty(dasherize(property)) })
    else
      css = dasherize(property) + ":" + maybeAddPx(property, value)
  } else {
    for (key in property)
      if (!property[key] && property[key] !== 0)
        this.each(function(){ this.style.removeProperty(dasherize(key)) })
      else
        css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
  }

  return this.each(function(){ this.style.cssText += ';' + css })
}
//css將font-size轉爲駝峯命名fontSize
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
//將駝峯命名轉爲普通css:fontSize=>font-size
function dasherize(str) {
  return str.replace(/::/g, '/')
         .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
         .replace(/([a-z\d])([A-Z])/g, '$1_$2')
         .replace(/_/g, '-')
         .toLowerCase()
}
//可能對數值須要添加'px'
function maybeAddPx(name, value) {
  return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}複製代碼

getComputedStyle
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
其是一個能夠獲取當前元素全部最終使用的CSS屬性值,返回一個樣式對象,只讀,其具體用法以下所示,同時讀取屬性的值是經過getPropertyValue去獲取:app

其與style的區別在於,後者是可寫的,同時後者只能獲取元素style屬性中的CSS樣式,而前者能夠獲取最終應用在元素上的全部CSS屬性對象。該方法的兼容性不錯,可以兼容IE9+,可是在IE9中,不可以讀取僞類的CSS。dom

相關文章
相關標籤/搜索