IE和Firefox中的getComputedStyle()和cssText

时间:2014-11-11 21:19:02

标签: javascript css internet-explorer

请参阅说明问题的this fiddle

我试图通过cssTextwhich returns a CSSStyleDeclaration object)获取<div>的{​​{1}}属性。这在Chrome中很好用(版本就在repos之外),但它在Firefox和IE10以及IE11中不起作用。实际上,window.getComputedStyle(element)是返回对象的属性,它只是一个空字符串。

它可能不适用于旧版本的IE,但我没有在这些版本中测试过。我似乎无法找到任何参考,特别是在最近的IE版本中没有工作。实际上Microsoft's documentation让我相信它应该工作,而实际上却没有(“设置或检索样式规则的持久表示”)。我正在尝试一个小橡皮鸭在这里调试,看看是否有一些明显的我错过了,或者也许是VM images我用来测试IE上的代码。我究竟做错了什么?谢谢!

编辑:我正在寻找的是一种获取应用于元素的CURRENT样式列表的方法,就像从Chrome中的cssText返回的对象中获取cssText时所发生的那样。这在Firefox或IE中不会发生。为了澄清,似乎使用IE中元素的getComputedStyle()属性检索通过样式表,样式标记和内联样式规则应用于元素的样式列表,但不是通过脚本以编程方式应用的样式。这可能是设计和预期的,但是:我如何复制从Chrome中的CSSStyleDeclaration对象使用style.cssText时所看到的行为(由cssText返回),但在Internet Explorer和Firefox中? / p>

1 个答案:

答案 0 :(得分:1)

您应该能够使用node.currentStyle来访问比cssText更可靠的特定样式属性。

http://msdn.microsoft.com/en-us/library/ie/ms535231%28v=vs.85%29.aspx

请注意,在此示例中,cssText不提供背景颜色。我不确定什么时候应该运行runtimeStyle但它似乎没有在javascript操作之前或之后工作。这些可能是IE中的错误。

注意:getComputedCSSText函数是用于演示目的的快速入侵,可能需要进行一些修改才能在生产环境中使用。

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type="text/css">

#MyStyle {

   background-color: #FF00FF;
   width: 40px;
   height: 40px;
}

</style>

<script type="text/javascript">


getComputedCSSText = function (node) {
   var s = [];
   for (var propertyName in node.currentStyle) {

       if ("string" == typeof(node.currentStyle[propertyName]) && node.currentStyle[propertyName] != "") {
          s[s.length] = (propertyName.replace(/[A-Z]/g, function(x) { return "-"+(x.toLowerCase())}))+": "+node.currentStyle[propertyName];
       }
   }

   return s.join('; ') + ";";
};



MyTest = function() {

    var node = document.getElementById('MyStyle');

    alert("[pre-js] runtimeStyle.width = " +node.runtimeStyle.width);
    alert("[pre-js] style.cssText = " + node.style.cssText);
    alert("[pre-js] currentStyle.width = " + node.currentStyle.width);
    alert("[pre-js] currentStyle.backgroundColor = " + node.currentStyle.backgroundColor);  


    node.style.width="99px";

    alert("[post-js] runtimeStyle.width = " +node.runtimeStyle.width);
    alert("[post-js] style.cssText = " + node.style.cssText);
    alert("[post-js] currentStyle.width = " + node.currentStyle.width);
    alert("[post-js] currentStyle.backgroundColor = " + node.currentStyle.backgroundColor);

    alert("[post-js] getComputedCSSText = " + getComputedCSSText(node));
};

</script>

</head>
<body>

<h1 id="MyStyle">FooBar!</h1>
<button onclick="MyTest()">Test</button>

</body>
</html>