您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript实现修改伪类样式

2025/11/15 8:11:08发布19次查看
项目中时常会需要用到使用javascript来动态控制为元素(:before,:after)的样式,但是我们都知道javascript或jquery并没有伪类选择器。本文我们主要介绍了javascript实现修改伪类样式的方法以及代码实现过程。
html
01393e88797e4f8093869b5866a90f61hi, this is a plain-old, sad-looking paragraph tag.94b3e26ee717c64999d7867364b1b4a3
css
.red::before { content: 'red'; color: red; }
方法一
使用javascript或者jquery切换<p>元素的类名,修改样式。
.green::before { content: 'green'; color: green; } $('p').removeclass('red').addclass('green');
方法二
在已存在的<style>中动态插入新样式。
document.stylesheets[0].addrule('.red::before','color: green'); document.stylesheets[0].insertrule('.red::before { color: green }', 0);
方法三
创建一份新的样式表,并使用javascript或jquery将其插入到<head>中
// create a new style tag var style = document.createelement("style"); // append the style tag to head document.head.appendchild(style); // grab the stylesheet object sheet = style.sheet // use addrule or insertrule to inject styles sheet.addrule('.red::before','color: green'); sheet.insertrule('.red::before { color: green }', 0);
jquery
$('<style>.red::before{color:green}</style>').appendto('head');
方法四
使用html5的data-属性,在属性中使用attr()动态修改。
<p class="red" data-attr="red">hi, this is plain-old, sad-looking paragraph tag.</p> .red::before { content: attr(data-attr); color: red; } $('.red').attr('data-attr', 'green');
相关推荐:
伪类选择器汇总
php中的伪类型和伪变量
php函数之常规参数函数和伪类型参数函数
以上就是javascript实现修改伪类样式的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product