繁体   English   中英

为什么javascript不返回样式属性?

[英]Why won't javascript return the style properties?

<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>

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

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

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

jsFiddle示例

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

为此,您需要getComputedStyle

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

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]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM