您好,欢迎访问一九零五行业门户网

如何用JavaScript修改伪类样式

我们都听说过css伪类但是并没有听说过javascript也有伪类,项目中时常会需要用到使用javascript来动态控制伪元素(:before,:after)的样式,但是我们都知道javascript或jquery并没有伪类选择器。这里总结一下几种常见的方法。
html
<p class="red">hi, this is a plain-old, sad-looking paragraph tag.</p> 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');
以上就是我们为大家整理的四种如何用javascript修改伪类样式的方法,希望对大家有帮助。
相关推荐:
css3伪类如何做3d按钮的实例分析
css中关于focus伪类的使用实例详解
伪类选择器汇总
以上就是如何用javascript修改伪类样式的详细内容。
其它类似信息

推荐信息