跟著Zepto學(xué)dom(二)

上期中我們看了元素選擇器、attr和class的源碼,今天我們來(lái)看下其append等的操作是如何進(jìn)行的。

clone: function(){
  return this.map(function(){ return this.cloneNode(true) })
}

this.cloneNode(flag)其返回this的節(jié)點(diǎn)的一個(gè)副本flag為true表示深度克隆,為了兼容性,該flag最好填寫(xiě)。

children: function(selector){
  return filtered(this.map(function(){ return children(this) }), selector)
}
function filtered(nodes, selector) {
//當(dāng)selector不為空的時(shí)候。
  return selector == null ? $(nodes) : $(nodes).filter(selector)
}
function children(element) {
//為了兼容性
  return 'children' in element ?
//返回 一個(gè)Node的子elements,在IE8中會(huì)出現(xiàn)包含注釋節(jié)點(diǎn)的情況,
//但在此處并不會(huì)調(diào)用該方法。
    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)
  }))
}
//這也是一個(gè)重點(diǎn),下面將重點(diǎn)分拆這個(gè)
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是為了檢測(cè)瀏覽器是否支持children方法,children兼容到IE9
Element.matches(selectorString)如果元素被指定的選擇器字符串選擇,否則該返回true,selectorString為css選擇器字符串。該方法的兼容性不錯(cuò)[element.matches的兼容性一覽](https://caniuse.com/#search=matches),在移動(dòng)端中完全可以放心使用,當(dāng)然在一些老版本上就不可以避免的要添加上一些前綴。如element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector ||element.matchesSelector所示。

注:其實(shí)在IE8中也可以通過(guò)polyfill的形式去實(shí)現(xiàn)該方法,如下所示:

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方法就如上面所示,其實(shí)其內(nèi)部只是調(diào)用了幾個(gè)不同的函數(shù)而已。

closest

closest: function(selector, context){
  var nodes = [], collection = typeof selector == 'object' && $(selector)
  this.each(function(_, node){
//當(dāng)node存在同時(shí)(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)
}
//檢測(cè)其是否為document節(jié)點(diǎn)
//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

這幾種方法都是先通過(guò)調(diào)用zepto.fragment該方法統(tǒng)一將content的內(nèi)容生成dom節(jié)點(diǎn),再進(jìn)行插入動(dòng)作。同時(shí)需要注意的是傳入的內(nèi)容可以為html字符串,dom節(jié)點(diǎn)或者節(jié)點(diǎn)組成的數(shù)組,如下所示:'<p>這是一個(gè)dom節(jié)點(diǎn)</p>',document.createElement('p'),['<p>這是一個(gè)dom節(jié)點(diǎn)</p>',document.createElement('p')]。

var adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ];
adjacencyOperators.forEach(function(operator, operatorIndex) {
//prepend和append的時(shí)候inside為1
  var inside = operatorIndex % 2
  $.fn[operator] = function(){
    var argType, nodes = $.map(arguments, function(arg) {
          var arr = []
//判斷arg的類(lèi)型,var arg = document.createElement('span');此時(shí)div類(lèi)型為object
//var arg = $('div'),此時(shí)類(lèi)型為array
//var arg = '<div>這是一個(gè)div</div>',此時(shí)類(lèi)型為string
          argType = type(arg)
//傳入為一個(gè)數(shù)組時(shí)
          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){
//當(dāng)為prepend和append的時(shí)候其parent為target
      parent = inside ? target : target.parentNode
//將所有的動(dòng)作全部調(diào)成before的動(dòng)作,其只是改變parent和target的不同
      target = operatorIndex == 0 ? target.nextSibling :
               operatorIndex == 1 ? target.firstChild :
               operatorIndex == 2 ? target :
               null
//檢測(cè)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)其在當(dāng)前節(jié)點(diǎn)的某個(gè)子節(jié)點(diǎn)之前再插入一個(gè)子節(jié)點(diǎn)
//如果parent為null則node將被插入到子節(jié)點(diǎn)的末尾。如果node已經(jīng)在DOM樹(shù)中,node首先會(huì)從DOM樹(shù)中移除
        parent.insertBefore(node, target)
//如果父元素在 document 內(nèi),則調(diào)用 traverseNode 來(lái)處理 node 節(jié)點(diǎn)及 node 節(jié)點(diǎn)的所有子節(jié)點(diǎn)。主要是檢測(cè) node 節(jié)點(diǎn)或其子節(jié)點(diǎn)是否為 script且沒(méi)有src地址。
        if (parentInDocument) traverseNode(node, function(el){
          if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
             (!el.type || el.type === 'text/javascript') && !el.src){
//由于在iframe中有獨(dú)立的window對(duì)象
//同時(shí)由于insertBefore插入腳本,并不會(huì)執(zhí)行腳本,所以要通過(guò)evel的形式去設(shè)置。
            var target = el.ownerDocument ? el.ownerDocument.defaultView : window
            target['eval'].call(target, el.innerHTML)
          }
        })
      })
    })
  }
  //該方法生成了方法名,同時(shí)對(duì)after、prepend、before、append、insertBefore、insertAfter、prependTo八個(gè)方法。其核心都是類(lèi)似的。
  $.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
//如果其只為一個(gè)節(jié)點(diǎn),里面沒(méi)有文本節(jié)點(diǎn)和子節(jié)點(diǎn)外,類(lèi)似<p></p>,則dom為p元素。
  if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
  if (!dom) {
//對(duì)html進(jìn)行修復(fù),如果其為<p/>則修復(fù)為<p></p>
    if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
//設(shè)置標(biāo)簽的名字。
    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中刪除一個(gè)節(jié)點(diǎn)并返回刪除的節(jié)點(diǎn)
      container.removeChild(this)
    })
  }
//檢測(cè)屬性是否為對(duì)象,如果為對(duì)象的化,則給元素設(shè)置屬性。
  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樣式時(shí)
  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轉(zhuǎn)為駝峰命名fontSize
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
//將駝峰命名轉(zhuǎn)為普通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()
}
//可能對(duì)數(shù)值需要添加'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))
其是一個(gè)可以獲取當(dāng)前元素所有最終使用的CSS屬性值,返回一個(gè)樣式對(duì)象,只讀,其具體用法如下所示,同時(shí)讀取屬性的值是通過(guò)getPropertyValue去獲?。?/p>

getComputedStyle.png

其與style的區(qū)別在于,后者是可寫(xiě)的,同時(shí)后者只能獲取元素style屬性中的CSS樣式,而前者可以獲取最終應(yīng)用在元素上的所有CSS屬性對(duì)象。該方法的兼容性不錯(cuò),能夠兼容IE9+,但是在IE9中,不能夠讀取偽類(lèi)的CSS。

offset

offset: function(coordinates){
  if (coordinates) return this.each(function(index){
    var $this = $(this),
        coords = funcArg(this, coordinates, index, $this.offset()),
        parentOffset = $this.offsetParent().offset(),
        props = {
          top:  coords.top  - parentOffset.top,
          left: coords.left - parentOffset.left
        }

    if ($this.css('position') == 'static') props['position'] = 'relative'
    $this.css(props)
  })
  if (!this.length) return null
//當(dāng)獲取的元素就是document該元素
  if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0]))
    return {top: 0, left: 0}
  var obj = this[0].getBoundingClientRect()
  return {
    left: obj.left + window.pageXOffset,
    top: obj.top + window.pageYOffset,
    width: Math.round(obj.width),
    height: Math.round(obj.height)
  }
}

getBoundingClientRect 該方法用于獲取某個(gè)元素相對(duì)于視窗的位置集合。
這個(gè)屬性特別需要注意的是DOM元素到瀏覽器可視范圍的距離并不包括文檔卷起來(lái)的部分。所以為了獲取元素在頁(yè)面上的位置并且解決瀏覽器的兼容性問(wèn)題就可以使用如下方法:

documentScrollTop = document.documentElement.scrollTop || window.pageYOffset
 || document.body.scrollTop;
documentScrollLeft = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
X = document.querySelector("#box").getBoundingClientRect().top+documentScrollTop;
Y = document.querySelector("#box").getBoundingClientRect().left+documentScrollLeft;

在IE9及以上的IE瀏覽器中該集合包含left,top,bottom,right,height,width六個(gè)屬性,但是在IE8中,其缺少width,height,但是在IE8中可以使用如下代碼得到width和height屬性:

height = document.getElementById("box").getBoundingClientRect().right-document.getElementById("box").getBoundingClientRect().left;
width = document.getElementById("box").getBoundingClientRect().bottom-document.getElementById("box").getBoundingClientRect().top;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問(wèn)答題47 /72 常見(jiàn)瀏覽器兼容性問(wèn)題與解決方案? 參考答案 (1)瀏覽器兼容問(wèn)題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 14,095評(píng)論 1 92
  • 原文 鏈接 關(guān)注公眾號(hào)獲取更多資訊 一、基本類(lèi)型介紹 1.1 Node類(lèi)型 DOM1級(jí)定義了一個(gè)Node接口,該接...
    前端進(jìn)階之旅閱讀 4,062評(píng)論 7 34
  • 本文整理自《高級(jí)javascript程序設(shè)計(jì)》 DOM(文檔對(duì)象模型)是針對(duì)HTML和XML文檔的一個(gè)API(應(yīng)用...
    SuperSnail閱讀 673評(píng)論 0 1
  • 剛組建就打擊 我還想著獨(dú)立后,我做產(chǎn)品,姜做后臺(tái),林做前端,三個(gè)人一起好好做出東西,然后找劉總投資呢。 一獨(dú)立后,...
    悟靜家閱讀 540評(píng)論 1 0
  • iOS實(shí)際上算是unix的一個(gè)分支,所以iOS上的多線程可以使用pthread。不過(guò)Apple另外提供了GCD來(lái)簡(jiǎn)...
    ax4c閱讀 548評(píng)論 0 0

友情鏈接更多精彩內(nèi)容