CSS 偽元素非常強大,常被用來製作 CSS 三角形提示等效果,能在不增加額外 HTML 標籤的情況下實現簡單樣式。過去 JavaScript 無法取得這些偽元素的屬性值,但現在有方法可以做到了。
看看下面的 CSS:
.element:before {
content: 'NEW';
color: rgb(255, 0, 0);
}
為了取得 .element:before 的 color 屬性,可以使用:
var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color')
把偽元素作為第二個參數傳進 window.getComputedStyle,就能取得它的 CSS 屬性了,很值得放進你的工具函式集。隨著愈來愈多瀏覽器支援偽元素,這個方法會很有用。
需要注意的是:window.getComputedStyle 在 IE9 以下不支援,getPropertyValue 必須搭配 getComputedStyle 使用;IE 雖支援 currentStyle 屬性,但仍無法取得偽元素的屬性。
<script type="text/javascript">
function getStyle( elem, name ) {
// 若屬性存在於 style[] 中,則它最近被設定過
if (elem.style[name]) {
return elem.style[name];
}
// 否則嘗試 IE 的方式
else if (elem.currentStyle) {
return elem.currentStyle[name];
}
// 或 W3C 的方法
else if (document.defaultView && document.defaultView.getComputedStyle) {
// 轉成 "text-align" 風格
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
}
else {
return null;
}
}
</script>
這個 getStyle 函式依序嘗試 element.style、currentStyle 與 getComputedStyle,做到跨瀏覽器相容地取得樣式值。