如何讀寫偽類元素的樣式?,讀寫虛擬元素樣式

來源:互聯網
上載者:User

如何讀寫偽類元素的樣式?,讀寫虛擬元素樣式

樣本: 

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.   
  4. <style>  
  5. .example::before {  
  6.     content: 'pseudoElement ';  
  7.     color: red;  
  8. }  
  9. </style>  



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

Js代碼  
  1. <script>  
  2. var str = window.getComputedStyle(document.querySelector('.example'), '::before').getPropertyValue('color');  
  3.   
  4. document.querySelector('#log').innerHTML = str;  
  5.   
  6. </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.   
  6.     //setProperty在這時候,會拋異常:  
  7.     try{  
  8.         window.getComputedStyle(document.querySelector('.example'), '::before').setProperty('color',"green");  
  9.     }catch(e){  
  10.         document.querySelector('#log').innerHTML =  e;  
  11.     }  
  12. </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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.