Zepto源碼分析之ie模塊

前言

Zepto中的ie模塊主要是改寫getComputedStyle瀏覽器API,代碼量不多,但也是其重要模塊之一。在看源代碼以前,咱們先回顧一下如何使用javascript

getComputedStyle

Window.getComputedStyle() 方法給出應用活動樣式表後的元素的全部CSS屬性的值,並解析這些值可能包含的任何基本計算。MDNcss

let style = window.getComputedStyle(element, [pseudoElt]);

elementhtml

element參數便是咱們要獲取樣式的元素java

pseudoEltgit

要匹配的僞元素字符串,對於普通元素來講需省略(null)github

結果ajax

特別重要的是該方法執行後返回的樣式是一個實時的 CSSStyleDeclaration 對象,當元素的樣式更改時,它會自動更新自己。json

<style>
 #elem{
   position: absolute;
   left: 100px;
   top: 200px;
   height: 100px;
 }
</style>

<div id="elem">dummy</div>
let $elem = document.querySelector('#elem')
let cssProps = getComputedStyle($elem, null)

let { width, height } = cssProps
console.log(width, height)

特別注意

第一個參數必須是Element對象(傳遞一個非節點元素,如 一個#text 節點, 將會拋出一個錯誤)MDN,這也多是Zepto要重寫它的緣由吧瀏覽器

源碼分析

;(function(){
  // getComputedStyle shouldn't freak out when called
  // without a valid element as argument
  // 重寫getComputedStyle
  // 第一個參數若是不是元素節點則會拋出錯誤,被catch捕獲,並被重寫。
  // 重寫後的方法,若是傳入的第一個參數不是元素節點,被catch捕獲,返回null,則不影響後續代碼的運行
  try {
    getComputedStyle(undefined)
  } catch(e) {
    var nativeGetComputedStyle = getComputedStyle
    window.getComputedStyle = function(element, pseudoElement){
      try {
        return nativeGetComputedStyle(element, pseudoElement)
      } catch(e) {
        return null
      }
    }
  }
})()

代碼很是簡單,瀏覽器在加載該模塊的時候,若是調用getComputedStyle第一個參數不爲元素節點時拋出錯誤,則被catch捕獲,並重寫該方法。重寫的方法中是另外一個try catch,若是後續再發生錯誤,將返回null,不阻礙後續js代碼的執行。緩存

結尾

以上即是Zepto ie模塊的源碼分析的所有,歡迎提出意見和建議。

文章記錄

ie模塊

  1. Zepto源碼分析之ie模塊(2017-11-03)

data模塊

  1. Zepto中數據緩存原理與實現(2017-10-03)

form模塊

  1. zepto源碼分析之form模塊(2017-10-01)

zepto模塊

  1. 這些Zepto中實用的方法集(2017-08-26)
  2. Zepto核心模塊之工具方法拾遺 (2017-08-30)
  3. 看zepto如何實現增刪改查DOM (2017-10-2)

event模塊

  1. mouseenter與mouseover爲什麼這般糾纏不清?(2017-06-05)
  2. 向zepto.js學習如何手動觸發DOM事件(2017-06-07)
  3. 誰說你只是"會用"jQuery?(2017-06-08)

ajax模塊

  1. 原來你是這樣的jsonp(原理與具體實現細節)(2017-06-11)
相關文章
相關標籤/搜索