简体   繁体   中英

Modify CSS selector :after with JavaScript

How do I access or modify pseudo-selectors like :after and :hover of CSS of an element through JavaScript (please no jQuery).

Example

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Progress bar example</title>
        <style type="text/css">
        .progressbar
        {
            position: relative;
            width: 100px;
            height: 10px;
            background-color: red;
        }

        .progressbar:after
        {
            content: "";
            position: absolute;
            width: 25%;
            height: 100%;
            background-color: blue;
        }
        </style>
    </head>

    <body>
        <div id="progressbar" class="progressbar" onclick="this.style.width='90%';"></div>
    </body>
</html>

Like you see I want to use somethink like a progress bar, so I can't simply exchange/add/remove a second class to an element. I would like to access the the width property of the progressbar:after (with the :after selector) class directly through JS. But how?

You could give this a try:

EDITED

//create new style element
var style = document.createElement("style");

//append the style
document.head.appendChild(style);

//take the stylesheet object
sheet = style.sheet

//add the rule to your stylesheet -- changed this line to .insertRule
sheet.insertRule('.progressbar::after { width: 50% }', 0);

Updated fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM