天天看點

如何讀寫僞類元素的樣式?

示例: 

Html代碼  

如何讀寫僞類元素的樣式?
  1. <p class="example" data-pseudo="(i'm content.)">Hi, this is a plain-old, sad-looking paragraph tag.</p>  
  2. <div id="log"></div>  
  3. <style>  
  4. .example::before {  
  5.     content: 'pseudoElement ';  
  6.     color: red;  
  7. }  
  8. </style>  

一、讀取,使用 window.getComputedStyle 方法: 

Js代碼  

如何讀寫僞類元素的樣式?
  1. <script>  
  2. var str = window.getComputedStyle(document.querySelector('.example'), '::before').getPropertyValue('color');  
  3. document.querySelector('#log').innerHTML = str;  
  4. </script>  

二、寫(修改) 

沒有辦法。至少沒有直接的方法,退而次之,隻能通過覆寫樣式的途徑來達到我們的目的。 

譬如:添加一個style元素,并寫入新的樣式;又或者是給目标元素添加不同的class,以達到控制的效果。 

示例: 

Html代碼  

如何讀寫僞類元素的樣式?
  1. <style id="pseudoStyle">  
  2. </style>  

Js代碼  

如何讀寫僞類元素的樣式?
  1. <script>  
  2.     document.querySelector('#pseudoStyle').sheet.insertRule(".example::before { color: green;}",0);  
  3.     //或者是  
  4.     document.querySelector('#pseudoStyle').sheet.addRule('.example::before','color: green');  
  5.     //setProperty在這時候,會抛異常:  
  6.     try{  
  7.         window.getComputedStyle(document.querySelector('.example'), '::before').setProperty('color',"green");  
  8.     }catch(e){  
  9.         document.querySelector('#log').innerHTML =  e;  
  10.     }  
  11. </script>  

僞類元素,有個屬性比較特殊:content。由于它的值可以定義為從元素的dom屬性擷取,進而可以實作js的直接讀寫。 

例如: 

Html代碼  

如何讀寫僞類元素的樣式?
  1. <style>  
  2. .example::before {  
  3.     content: attr(data-pseudo);  
  4.     color: red;  
  5. }  
  6. </style>  

Js代碼  

如何讀寫僞類元素的樣式?
  1. <script>  
  2.     document.querySelector('.example').setAttribute("data-pseudo","new content!");  
  3. </script>  

附錄: 

1. styleSheet對象的方法、屬性和浏覽器相容,參考:http://help.dottoro.com/ljpatulu.php 

2. getComputedStyle方法,參考:http://help.dottoro.com/ljscsoax.php , https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle

php