javascript - 为什么我在加载页面时无法获取这些 css 属性?

标签 javascript html css

Possible Duplicate:
Get a CSS value with JavaScript

你能告诉我为什么我在加载页面时无法获取这些CSS属性吗?

code at jsFiddle

javascript:

function aviso(){
    alert("top: "+document.getElementById("divRojo").style.top);
    alert("position: "+document.getElementById("divRojo").style.position);
}

HTML:

<html>
    <head>
        <style type="text/css">
            #divRojo {
                width:100px;
                height:100px;
                background:red;
                left:200px;
                top:200px;
                position:static;
        }
    </style>
</head>

<body onload="aviso()">
    <div id="divRojo">
        Div Rojo
    </div>
</body>

</html>

提前致谢

最佳答案

这是因为 DOMElement.style 属性包含内联样式 - 它不包含通过 CSS 应用的样式规则。

使用getComputedStyle获取应用的样式:

var el = document.getElementById("divRojo");
alert(window.getComputedStyle(el).top);
alert(window.getComputedStyle(el).position);

JSFiddle

关于javascript - 为什么我在加载页面时无法获取这些 css 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13504524/

相关文章:

css - Div 无法正常展开

javascript - 将 JSON 文件转换为 Javascript 对象

css - IE9 中这些@font-face 字体有什么问题?

javascript - 如何让它等到一切完成直到下一次迭代

javascript - 为什么我的 getElementsByTagName 返回一个空的 NodeList?

javascript - 如何在单击 TR 时选择它并在单击另一个 TR 时删除选择

javascript - $.post函数,返回为空

javascript - span 上 div 指定条件的倒计时

html - 显示内联导致元素被进一步向下推

html - 嵌套容器中的整页宽度规则