css伪元素的js写法,给before跟after伪元素设置js效果的5种方法

本文介绍了5种通过JavaScript控制CSS伪元素:before和:after的方法,包括动态嵌入CSS样式、添加类名、利用setAttribute自定义content值等技巧。

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

给before和after伪元素设置js效果的5种方法

前面的话

无法直接给before和after伪元素设置js效果

例子说明

现在需要为(id为box,内容为"我是测试内容"的div)添加(:before内容为"前缀",颜色为红色的伪元素)

Document
我是测试内容

var oBox = document.getElementById('box');

解决办法

【方法一】动态嵌入CSS样式

IE8-浏览器将

function loadStyleString(css){var style = document.createElement("style");

style.type= "text/css";try{

style.appendChild(document.createTextNode(css));

}catch(ex){

style.styleSheet.cssText=css;

}var head = document.getElementsByTagName('head')[0];

head.appendChild(style);

}

loadStyleString("#box:before{content:'前缀';color: red;}");

【方法二】添加自带伪元素的类名

oBox.className= 'change';

[缺点]此方法无法控制伪元素里面的content属性的值

【方法三】利用setAttribute实现自定义content内容

oBox.setAttribute('data-beforeData','前缀');

[注意]此方法只可用setAttribute实现,经测试用dataset方法无效

【方法四】添加样式表

firefox浏览器不支持addRule()方法,IE8-浏览器不支持insertRule()方法。兼容写法如下:

function insertRule(sheet,ruleKey,ruleValue,index){return sheet.insertRule ? sheet.insertRule(ruleKey+ '{' + ruleValue + '}',index) : sheet.addRule(ruleKey,ruleValue,index);

}

insertRule(document.styleSheets[0],'#box:before','content:"前缀";color: red;',0)

[缺点]该方法必须有内部

【方法五】修改样式表

先使用方法四添加空的样式表,然后获取新生成的

function loadStyleString(css){var style = document.createElement("style");

style.type= "text/css";try{

style.appendChild(document.createTextNode(css));

}catch(ex){

style.styleSheet.cssText=css;

}var head = document.getElementsByTagName('head')[0];

head.appendChild(style);

}

loadStyleString('');

document.head.getElementsByTagName('style')[1].innerHTML = "#oBox:before{color:" + colorValue + ";}";

[注意]只能使用getElementsByTagName('style')[1]的方法,经测验使用stylesheets[1]方法无效

DEMO

<演示框>点击下列相应属性值可进行演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值