首页  >  文章  >  web前端  >  如何用JavaScript修改伪类样式

如何用JavaScript修改伪类样式

小云云
小云云原创
2017-11-29 09:42:163301浏览

我们都听说过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: &#39;red&#39;;
color: red;
}

方法一

使用JavaScript或者jQuery切换e388a4556c0f65e1904146cc1a846bee元素的类名,修改样式。

.green::before {
content: &#39;green&#39;;
color: green;
}
$(&#39;p&#39;).removeClass(&#39;red&#39;).addClass(&#39;green&#39;);

方法二

在已存在的c9ccee2e6ea535a969eb3f532ad9fe89中动态插入新样式。

document.styleSheets[0].addRule(&#39;.red::before&#39;,&#39;color: green&#39;);
document.styleSheets[0].insertRule(&#39;.red::before { color: green }&#39;, 0);

方法三

创建一份新的样式表,并使用JavaScript或jQuery将其插入到93f0f5c25f18dab9d176bd4f6de5d30e中

// 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(&#39;.red::before&#39;,&#39;color: green&#39;);
sheet.insertRule(&#39;.red::before { color: green }&#39;, 0);

jQuery

$(&#39;<style>.red::before{color:green}</style>&#39;).appendTo(&#39;head&#39;);

方法四

使用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;
}
$(&#39;.red&#39;).attr(&#39;data-attr&#39;, &#39;green&#39;);

以上就是我们为大家整理的四种如何用JavaScript修改伪类样式的方法,希望对大家有帮助。

相关推荐:

CSS3伪类如何做3D按钮的实例分析

CSS中关于focus伪类的使用实例详解

伪类选择器汇总

以上是如何用JavaScript修改伪类样式的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn