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后可以取得值?

阅读 6.3k
2 个回答
✓ 已被采纳新手上路,请多包涵

已解决。原因是CSS变量不是采用内联样式,而document.documentElement.style.getPropertyValue只能获取内联样式的值,所以get值为空。同样的document.documentElement.style.setProperty赋值操作是会作为内联样式添加的,所以此时再get便有值

document.styleSheets[0].cssRules[0].style.getPropertyValue('--bg_color')
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题