CSS偽元素非常強(qiáng)大,它經(jīng)常被用來(lái)創(chuàng)建CSS三角形提示,使用CSS偽元素可以實(shí)現(xiàn)一些簡(jiǎn)單的效果但又不需要增加額外的HTML標(biāo)簽。有一點(diǎn)就是Javascript無(wú)法獲取到這些CSS屬性值,但現(xiàn)在有一種方法可以獲取到:
看看下面的CSS代碼:
1
2
3
4
5
6
7
|
.element:before { content : 'NEW' ; color : rgb ( 255 , 0 , 0 ); }.element:before { content : 'NEW' ; color : rgb ( 255 , 0 , 0 ); } |
為了獲取到.element:before的顏色屬性,你可以使用下面的代碼:
1
2
3
4
5
|
var color = window.getComputedStyle( document.querySelector( '.element' ), ':before' ).getPropertyValue( 'color' ) var color = window.getComputedStyle( document.querySelector( '.element' ), ':before' ).getPropertyValue( 'color' ) |
把偽元素作為第二個(gè)參數(shù)傳到window.getComputedStyle方法中就可以獲取到它的CSS屬性了。把這段代碼放到你的工具函數(shù)集里面去吧。隨著偽元素被越來(lái)越多的瀏覽器支持,這個(gè)方法會(huì)很有用的。
譯者注:window.getComputedStyle方法在IE9以下的瀏覽器不支持,getPropertyValue必須配合getComputedStyle方法一起使用。IE支持CurrentStyle屬性,但還是無(wú)法獲取偽元素的屬性。
準(zhǔn)確獲取指定元素 CSS 屬性值的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<script type= "text/javascript" > function getStyle( elem, name ) { //如果該屬性存在于style[]中,則它最近被設(shè)置過(guò)(且就是當(dāng)前的) 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) { //它使用傳統(tǒng)的"text-Align"風(fēng)格的規(guī)則書(shū)寫(xiě)方式,而不是"textAlign" name = name.replace(/([A-Z])/g, "-$1" ); name = name.toLowerCase(); //獲取style對(duì)象并取得屬性的值(如果存在的話) var s = document.defaultView.getComputedStyle(elem, "" ); return s && s.getPropertyValue(name); //否則,就是在使用其它的瀏覽器 } else { return null ; } } </script> |