CSS偽元素非常強大,它經常被用來創建CSS三角形提示,使用CSS偽元素可以實現一些簡單的效果但又不需要增加額外的HTML標簽。有一點就是Javascript無法獲取到這些CSS屬性值,但現在有一種方法可以獲取到:
看看下面的CSS代碼:
.element:before {
content: 'NEW';
color: rgb(255, 0, 0);
}.element:before {
content: 'NEW';
color: rgb(255, 0, 0);
}
為了獲取到.element:before的顏色屬性,你可以使用下面的代碼:
var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color')var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color')
把偽元素作為第二個參數傳到window.getComputedStyle方法中就可以獲取到它的CSS屬性了。把這段代碼放到你的工具函數集裡面去吧。隨著偽元素被越來越多的浏覽器支持,這個方法會很有用的。
譯者注:window.getComputedStyle方法在IE9以下的浏覽器不支持,getPropertyValue必須配合getComputedStyle方法一起使用。IE支持CurrentStyle屬性,但還是無法獲取偽元素的屬性。
准確獲取指定元素 CSS 屬性值的方法。
<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"風格的規則書寫方式,而不是"textAlign"
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();
//獲取style對象並取得屬性的值(如果存在的話)
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
//否則,就是在使用其它的浏覽器
}
else
{
return null;
}
}
</script>