id.styles什么也没显示

id.styles is showing nothing

本文关键字:显示 什么 styles id      更新时间:2023-09-26

>我不确定我是否会完全发疯,或者我的电脑是否有问题。

我在下面有一段简单的 JavaScript,但是当我控制台记录样式对象时,它完全是空的。尽管有问题的元素显然附加了样式。

<!doctype html>
<html>
<head>
<style>
    #para{  
        width: 100px;
        height: 100px;
        position: absolute;
        left: 200px;
        top: 10px;
        border: 1px solid red;      
    }
</style>
</head>
<body>
    <div id="para" class="paraDiv">This is the div</div>
<script>
        window.onload = function(){
            var d = document.getElementById('para');    
            console.dir(d);
            console.log(d.style.top);
        }
</script>
</body>
</html>

style 属性仅获取有关通过元素的 style 属性内联应用的样式的信息。它不包含有关从其他元素继承或在样式表中声明的样式的任何信息。

相反,您需要window.getComputedStyle,这将为您提供所需的信息。

console.log(getComputedStyle(para).top);
相关文章: