首页 > 网站 > WEB开发 > 正文

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

2024-04-27 14:30:06
字体:
来源:转载
供稿:网友
如何读写伪类元素的样式?

示例:

Html代码收藏代码
  1. <pclass="example"data-pseudo="(i'mcontent.)">Hi,thisisaplain-old,sad-lookingparagraphtag.</p>
  2. <divid="log"></div>
  3. <style>
  4. .example::before{
  5. content:'pseudoElement';
  6. color:red;
  7. }
  8. </style>

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

Js代码收藏代码
  1. <script>
  2. varstr=window.getComputedStyle(document.querySelector('.example'),'::before').getPRopertyValue('color');
  3. document.querySelector('#log').innerHTML=str;
  4. </script>

二、写(修改)没有办法。至少没有直接的方法,退而次之,只能通过覆盖样式的途径来达到我们的目的。譬如:添加一个style元素,并写入新的样式;又或者是给目标元素添加不同的class,以达到控制的效果。示例:

Html代码收藏代码
  1. <styleid="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","newcontent!");
  3. </script>

附录:1. styleSheet对象的方法、属性和浏览器兼容,参考:http://help.dottoro.com/ljpatulu.php2. getComputedStyle方法,参考:http://help.dottoro.com/ljscsoax.php , https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表