Home  >  Article  >  Web Front-end  >  How to modify pseudo-class styles with JavaScript

How to modify pseudo-class styles with JavaScript

小云云
小云云Original
2017-11-29 09:42:163347browse

We have all heard of CSS pseudo-classes but not that JavaScript also has pseudo-classes. In projects, we often need to use JavaScript to dynamically control the styles of pseudo-elements (:before,:after), but we all know There are no pseudo-class selectors in JavaScript or jQuery. Here is a summary of several common methods.

HTML

<p class="red">Hi, this is a plain-old, sad-looking paragraph 
tag.</p>
CSS
.red::before {
content: &#39;red&#39;;
color: red;
}

Method 1

Use JavaScript or jQuery to switch the class name of the e388a4556c0f65e1904146cc1a846bee element and modify the style.

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

Method 2

Dynamicly insert a new style into the existing c9ccee2e6ea535a969eb3f532ad9fe89.

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

Method 3

Create a new style sheet and insert it into the 93f0f5c25f18dab9d176bd4f6de5d30e using JavaScript or jQuery

// 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;);

Method 4

Use the HTML5 data-attribute and use attr() to dynamically modify it in the attribute.

<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;);

The above are the four methods we have compiled for you on how to use JavaScript to modify pseudo-class styles. We hope it will be helpful to everyone.

Related recommendations:

Example analysis of how CSS3 pseudo-classes make 3D buttons

Detailed explanation of usage examples of focus pseudo-classes in CSS

Summary of pseudo-class selectors

The above is the detailed content of How to modify pseudo-class styles with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn