[getComputedStyle](https://developer.mozilla.org/zh-TW/docs/Web/API/Window/getComputedStyle) === 返回 [CSSStyleDeclaration](https://www-w3schools-com.translate.goog/jsref/obj_cssstyledeclaration.asp?_x_tr_sl=en&_x_tr_tl=zh-TW&_x_tr_hl=zh-TW&_x_tr_pto=sc) object(取得 CSS 屬性和值)。 讀取的是最終樣式,包括內聯樣式、嵌入樣式、外部樣式。唯讀,只能獲取無法改變。 > window . getComputedStyle ( element , pseudoElement ) - element 必選,需要獲取的元素 - pseudoElement 可選,需要獲取的偽元素,不需要可以填寫 `null`,或是直接省略 ### 範例:取得偽元素的屬性 ```jsx const element = document.getElementById("test"); const cssObj = window.getComputedStyle(element, ":first-letter") let size = cssObj.getPropertyValue("font-size"); ``` - `getComputedStyle` 取得屬性名稱 - [`getPropertyValue`](https://hackmd.io/de88lOQ7TsCk4UWJqPWqWQ) 取得屬性的值 ### 範例:取得屬性 ```jsx window.getComputedStyle(dome).color; ``` > [Dome](https://codepen.io/betty-hu/pen/YzvKvva?editors=1111) 瀏覽器相容 --- | IE9 、Chrome、Firefox、Opera、Safar | IE5 / 6 / 7 / 8 | | -------- | -------- | | window . getComputedStyle ( element, null ) [ "attributeName" ] | element . currentStyle [ attributeName ] | ```jsx getStyle(box1, "backgroundColor"); function getStyle (obj, attributeName) { if(obj.currentStyle){ //如果存在物件,則是在ie瀏覽器 return obj.currentStyle[attributeName]; }else { //其他瀏覽器 return window.getComputedStyle(obj, null)[attributeName]; } } ``` 與 element.style 的異同 --- - element.style 讀取的只有元素的內聯樣式。支持讀取也支持寫入,可以通過 element.style 修改元素樣式。 - getComputedStyle 讀取的是最終樣式,包括內聯樣式、嵌入樣式、外部樣式。僅支持讀取,不支持寫入。 可以通過使用 getComputedStyle 讀取樣式,再通過 element.style 修改樣式。 實例 --- - [伸縮視窗](https://codepen.io/betty-hu/pen/GRdgQob?editors=1111)