跟著Zepto學dom(二)

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

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

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

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中會出現(xiàn)包含注釋節(jié)點的情況,
//但在此處并不會調用該方法。
    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的兼容性一覽](https://caniuse.com/#search=matches),在移動端中完全可以放心使用,當然在一些老版本上就不可以避免的要添加上一些前綴。如element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector ||element.matchesSelector所示。

注:其實在IE8中也可以通過polyfill的形式去實現(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ù)而已。

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節(jié)點
//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該方法統(tǒng)一將content的內容生成dom節(jié)點,再進行插入動作。同時需要注意的是傳入的內容可以為html字符串,dom節(jié)點或者節(jié)點組成的數(shù)組,如下所示:'<p>這是一個dom節(jié)點</p>',document.createElement('p'),['<p>這是一個dom節(jié)點</p>',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)
//傳入為一個數(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){
//當為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)其在當前節(jié)點的某個子節(jié)點之前再插入一個子節(jié)點
//如果parent為null則node將被插入到子節(jié)點的末尾。如果node已經(jīng)在DOM樹中,node首先會從DOM樹中移除
        parent.insertBefore(node, target)
//如果父元素在 document 內,則調用 traverseNode 來處理 node 節(jié)點及 node 節(jié)點的所有子節(jié)點。主要是檢測 node 節(jié)點或其子節(jié)點是否為 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插入腳本,并不會執(zhí)行腳本,所以要通過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
//如果其只為一個節(jié)點,里面沒有文本節(jié)點和子節(jié)點外,類似<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中刪除一個節(jié)點并返回刪除的節(jié)點
      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()
}
//可能對數(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))
其是一個可以獲取當前元素所有最終使用的CSS屬性值,返回一個樣式對象,只讀,其具體用法如下所示,同時讀取屬性的值是通過getPropertyValue去獲?。?/p>

getComputedStyle.png

其與style的區(qū)別在于,后者是可寫的,同時后者只能獲取元素style屬性中的CSS樣式,而前者可以獲取最終應用在元素上的所有CSS屬性對象。該方法的兼容性不錯,能夠兼容IE9+,但是在IE9中,不能夠讀取偽類的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
//當獲取的元素就是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 該方法用于獲取某個元素相對于視窗的位置集合。
這個屬性特別需要注意的是DOM元素到瀏覽器可視范圍的距離并不包括文檔卷起來的部分。所以為了獲取元素在頁面上的位置并且解決瀏覽器的兼容性問題就可以使用如下方法:

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六個屬性,但是在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;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 14,199評論 1 92
  • 原文 鏈接 關注公眾號獲取更多資訊 一、基本類型介紹 1.1 Node類型 DOM1級定義了一個Node接口,該接...
    前端進階之旅閱讀 4,071評論 7 34
  • 本文整理自《高級javascript程序設計》 DOM(文檔對象模型)是針對HTML和XML文檔的一個API(應用...
    SuperSnail閱讀 684評論 0 1
  • 剛組建就打擊 我還想著獨立后,我做產(chǎn)品,姜做后臺,林做前端,三個人一起好好做出東西,然后找劉總投資呢。 一獨立后,...
    悟靜家閱讀 543評論 1 0
  • iOS實際上算是unix的一個分支,所以iOS上的多線程可以使用pthread。不過Apple另外提供了GCD來簡...
    ax4c閱讀 561評論 0 0

友情鏈接更多精彩內容