【问题标题】:Why won't javascript return the style properties?为什么javascript不返回样式属性?
【发布时间】:2013-02-01 10:05:39
【问题描述】:
<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,我发现我可以设置属性但无法返回它们。为什么?

【问题讨论】:

  • 可以通过这种方式访问​​属性,但是#foo 没有 style 属性?
  • 有没有办法可以引用通过级联应用的样式?
  • @Bergi 有没有办法可以引用css文件中的宽度?还是我应该在 html 标签中设置 width 属性?
  • 设置style 属性(通过el.style.width = …;)对于单个元素来说是最简单和最好的。但是,引用和更改应用的样式表是possible

标签: javascript dom


【解决方案1】:

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

为此,您需要getComputedStyle

【讨论】:

  • 有没有办法可以引用css中的宽度?
【解决方案2】:

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

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

jsFiddle example

【讨论】:

    【解决方案3】:

    根据您需要访问的属性,您还有其他方法,例如 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]
    }
    

    【讨论】:

    • 好的。如何获取cssprop以便将其传递给函数 getStyle()?
    • cssprop是参数,可以放自己喜欢的样式属性,宽度,高度,颜色等...可以像getStyle(element, 'height');例如
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多