前言
Zepto中的ie模塊主要是改寫
getComputedStyle
瀏覽器API,代碼量很少,但也是其重要模塊之一。在看源代碼之前,我們先回顧一下如何使用
getComputedStyle
Window.getComputedStyle() 方法給出應用活動樣式表后的元素的所有CSS屬性的值,并解析這些值可能包含的任何基本計算。MDN
let style = window.getComputedStyle(element, [pseudoElt]);
element
element參數即是我們要獲取樣式的元素
pseudoElt
要匹配的偽元素字符串,對于普通元素來說需省略(null)
結果
特別重要的是該方法執行后返回的樣式是一個實時的 CSSStyleDeclaration 對象,當元素的樣式更改時,它會自動更新本身。
<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模塊
- Zepto源碼分析之ie模塊(2017-11-03)
data模塊
- Zepto中數據緩存原理與實現(2017-10-03)
form模塊
- zepto源碼分析之form模塊(2017-10-01)
zepto模塊
- 這些Zepto中實用的方法集(2017-08-26)
- Zepto核心模塊之工具方法拾遺 (2017-08-30)
- 看zepto如何實現增刪改查DOM (2017-10-2)
event模塊
- mouseenter與mouseover為何這般糾纏不清?(2017-06-05)
- 向zepto.js學習如何手動觸發DOM事件(2017-06-07)
- 誰說你只是"會用"jQuery?(2017-06-08)
ajax模塊
- 原來你是這樣的jsonp(原理與具體實現細節)(2017-06-11)