0
<html>
<head>
    <title>Return Width</title>
    <style type="text/css">
        #foo { background: green; width: 80px; }
    </style>
    <script type="text/javascript">
        function getWidth() {
            alert(document.getElementById("foo").style.width);
        }
    </script>
</head>
<body>
<div id="foo" onClick="getWidth()">
    Hello World
</div>

我一直在尝试返回几个属性,包括widthandbackgroundColor我发现我可以设置属性但我不能返回它们。为什么?

4

3 回答 3

3

这仅适用于内联样式。将 getComputedStyle用于通过非内联样式设置的 CSS。

function getWidth() {
    var elem = document.getElementById("foo");
    var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("width");
    alert(theCSSprop);
}

jsFiddle 示例

于 2013-02-16T14:49:53.967 回答
2

style属性引用直接应用于元素的样式(通过属性stylestyle属性)。它不引用通过级联应用的样式。

为此,您想要getComputedStyle.

于 2013-02-16T14:49:04.657 回答
1

根据您需要访问的属性,您还有其他方法,例如getComputedStyles 在 ie7 和 ie8 上不起作用,尽管您可以尝试这个,是跨浏览offsetwidthoffsetheight.

function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}
于 2013-02-16T14:57:43.903 回答