簡體   English   中英

用JavaScript修改CSS選擇器:after

[英]Modify CSS selector :after with JavaScript

如何通過JavaScript訪問或修改元素CSS的偽選擇器,如:after:hover (請不要使用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屬性。 但是如何?

您可以嘗試一下:

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

更新的小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM