L0j*_*j1k 6 javascript css internet-explorer
我试图获取cssText
一个<div>
via 的属性window.getComputedStyle(element)
(返回一个CSSStyleDeclaration对象).这在Chrome中很好用(版本就在repos之外),但它在Firefox和IE10以及IE11中不起作用.实际上,它cssText
是返回对象的属性,它只是一个空字符串.
它可能无法在旧版本的IE中使用,但我没有在那些版本中测试它.我似乎无法找到任何参考,特别是在最近的IE版本中没有工作.实际上,微软的文档让我相信它应该工作,而实际上却没有("设置或检索样式规则的持久表示").我正在尝试一个小橡皮鸭在这里调试,看看是否有一些明显的我错过了,或者也许它是我用来测试IE上的代码的VM图像.我究竟做错了什么?谢谢!
编辑:我正在寻找的是一种获取应用于元素的CURRENT样式列表的方法,就像cssText
从getComputedStyle()
Chrome中返回的对象获取一样,但在Firefox或IE中不会发生.为了澄清,似乎使用style.cssText
IE中元素的属性来检索通过样式表,样式标记和内联样式规则应用于元素的样式列表,但不是通过脚本以编程方式应用的样式.这可能是设计和预期的,但是:我如何复制cssText
在Chrome中使用CSSStyleDeclaration对象时看到的行为(由返回getComputedStyle()
),但在Internet Explorer和Firefox中?
您应该能够使用 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>
Run Code Online (Sandbox Code Playgroud)