天天看点

如何读写伪类元素的样式?

示例: 

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