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实现修改伪类样式的详细内容。
