无法使用 document.querySelector 从内部样式表中获取属性.或 document.getElemen



也许我疯了或累了。但是我不明白为什么我突然无法从内部样式表中检索我的元素样式。但是如果我使样式内联,它会起作用。一个简单的代码示例:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #box_1  {padding:1em;width:25%;background-color:blue;color:red;font-size:2em;font-weight:bolder}
        #test_1 {position:absolute;bottom:1em;right:1em;font-size:2em;}
    </style>
</head>
<body>
<div id="box_1" >
    BOX 1
</div>
<button id="test_1" type="button" onclick="test_1()">Alert font-color<br/> from box 1</button>
</body>
<script>
    function test_1()
    {
        var str=document.querySelector("#box_1").style.color;
        alert(str);
    }
</script>
</html>

如果要访问元素的有效样式(包括全局定义的 CSS),请使用 getComputedStyle()

function test_1() {
  var str=window.getComputedStyle( document.querySelector("#box_1") )
                .getPropertyValue ( 'color' );
  alert(str);
}

style属性本身仅指属性style元素以及使用 JavaScript 设置的样式。有关详细信息,请参阅相应的 MDN 文档。

相关内容

最新更新