Javascript擷取CSS虛擬元素屬性的實現代碼,css偽

來源:互聯網
上載者:User

Javascript擷取CSS虛擬元素屬性的實現代碼,css偽

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>

javascript或者jquery對應的方法中有沒有可以更改css虛擬元素:before,:after樣式的?

貌似麼有啊……javascript修改css其實就是寫到元素的style屬性上,:before,:after偽類是虛擬元素……怎麼改啊……要是非得要修改的話,建議切換.info的class試試,設計兩個有:before的class,需要修改是切換有class的那個元素 ,比如
.info:before{
content:"infomation";
border:1px solid #ccc;
}
.info_other:before{
content:"infomation";
border:2px solid #000;
},
然後需要修改的時候把.info改成.info_other
 
javaScript怎擷取css樣式屬性

this.style.color
this.style.display
按照這樣的方式擷取
this表示你要擷取樣式的對象,可以通過document.getElementById等來擷取對象,這就不用我多說了吧
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.