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

本文介绍了如何使用window.getComputedStyle方法读取CSS伪元素的样式,如颜色等属性,并探讨了直接修改伪元素样式的局限性及替代方案。此外,还讨论了通过设置伪元素的内容属性实现与JavaScript交互的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例:

<p class="example" data-pseudo="(i'm content.)">Hi, this is a plain-old, sad-looking paragraph tag.</p>
<div id="log"></div>

<style>
.example::before {
content: 'pseudoElement ';
color: red;
}
</style>


[b]一、读取,使用 window.getComputedStyle 方法:[/b]


<script>
var str = window.getComputedStyle(document.querySelector('.example'), '::before').getPropertyValue('color');

document.querySelector('#log').innerHTML = str;

</script>

[b]
二、写(修改)[/b]

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

示例:


<style id="pseudoStyle">
</style>



<script>
document.querySelector('#pseudoStyle').sheet.insertRule(".example::before { color: green;}",0);
//或者是
document.querySelector('#pseudoStyle').sheet.addRule('.example::before','color: green');

//setProperty在这时候,会抛异常:
try{
window.getComputedStyle(document.querySelector('.example'), '::before').setProperty('color',"green");
}catch(e){
document.querySelector('#log').innerHTML = e;
}
</script>


伪类元素,有个属性比较特殊:content。由于它的值可以定义为从元素的dom属性获取,从而可以实现js的直接读写。
例如:


<style>
.example::before {
content: attr(data-pseudo);
color: red;
}
</style>



<script>
document.querySelector('.example').setAttribute("data-pseudo","new content!");
</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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值