Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

JS getPropertyValue获取CSS变量值为空?

问题情景:

定义好css变量后使用js获取修改css变量时发现在使用getPropertyValue方法无法取到css变量的值、为空,但是在setProperty后再getPropertyValue则能取到值。
`

<head>
    <style>
        :root {
            --bg_color: green;
        }
        body {
            background-color: var(--bg_color);
        }
    </style>
</head>
<body>
    <script>
        var mystyle = document.documentElement.style;
        console.log('bgcolor=' + mystyle.getPropertyValue("--bg_color").trim());
        setTimeout("changBgcolor()", 3000);

        function changBgcolor() {
            mystyle.setProperty("--bg_color", "red");
            console.log('在setProperty后bgcolor=' + mystyle.getPropertyValue("--bg_color").trim());
        }
    </script>
</body>

`

输出结果是:

image

期待解答的问题:

为啥初次getPropertyValue无法取得css变量的值,而在setProperty后可以取得值?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

还发现了一个问题,就是如果CSS变量不是在根伪类上:root声明的话,虽然setProperty可以修改值,getPropertyValue可以获取到修改后的值,但是对应的网页不会跟随变化

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JS Bin</title>
        <style>
            :root {
                /* --bg_color: green; */
            }

            body {
                align-items: center;
                --bg_color: green;
            }

            div {
                width: 500px;
                height: 18.75rem;
                background-color: var(--bg_color);
            }
        </style>
    </head>
    <body>
        <div id="div">
            <button onclick="changBgcolor()">点击换背景色</button>
        </div>
        <script>
            var mystyle = document.documentElement.style;
            console.log('bgcolor=' + mystyle.getPropertyValue("--bg_color").trim());

            function changBgcolor() {
                if (mystyle.getPropertyValue("--bg_color").trim() === "green") {
                    mystyle.setProperty("--bg_color", "red");
                } else {
                    mystyle.setProperty("--bg_color", "green");
                }
                console.log('在setProperty后bgcolor=' + mystyle.getPropertyValue("--bg_color").trim());
            }
        </script>
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...