Zepto中的ie模塊主要是改寫
getComputedStyle
瀏覽器API,代碼量不多,但也是其重要模塊之一。在看源代碼以前,咱們先回顧一下如何使用javascript
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模塊
data模塊
form模塊
zepto模塊
event模塊
ajax模塊