使用JavaScript修改CSS选择器:之后

Modify CSS selector :after with JavaScript

本文关键字:之后 选择器 CSS JavaScript 修改 使用      更新时间:2023-09-26

如何通过JavaScript访问或修改元素的CSS的伪选择器,如:在之后和(请不要使用jQuery)。

示例

<!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>

就像你看到的那样,我想使用进度条之类的东西,所以我不能简单地交换/添加/删除元素的第二个类。我想直接通过JS访问progressbar:after(使用:after选择器)类的width属性。但是怎么做呢?

您可以尝试一下:

已编辑

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

更新的fiddle