Home  >  Article  >  Web Front-end  >  JavaScript implements modifying pseudo-class styles

JavaScript implements modifying pseudo-class styles

小云云
小云云Original
2017-12-07 15:58:131608browse

In projects, we often need to use JavaScript to dynamically control the style of elements (:before,:after), but we all know that JavaScript or jQuery does not have pseudo-class selectors. In this article, we mainly introduce the method of modifying pseudo-class styles in JavaScript and the code implementation process.

HTML

6f23bfb838f442699a99d538155cf763Hi, this is a plain-old, sad-looking paragraph tag.94b3e26ee717c64999d7867364b1b4a3

CSS


.red::before {
content: 'red';
color: red;
}


Method 1

Use JavaScript or jQuery to switch e388a4556c0f65e1904146cc1a846beeThe class name of the element, modify the style.


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


Method 2

Dynamically insert new styles into existing c9ccee2e6ea535a969eb3f532ad9fe89.


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


Method 3

Create a new stylesheet 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('.red::before','color: green');
sheet.insertRule('.red::before { color: green }', 0);


jQuery


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


Method 4

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


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

Related recommendations:

Summary of pseudo-class selectors

Pseudo-types in PHP And pseudo-variables

php function regular parameter function and pseudo-type parameter function

The above is the detailed content of JavaScript implements modifying pseudo-class styles. 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