使用JavaScript获取元素的所有CSS样式 [英] Get all CSS styles of an element with JavaScript

查看:126
本文介绍了使用JavaScript获取元素的所有CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法来选择JavaScript的元素的所有CSS规则吗?我不是在寻找一个特定的解决方案,只要一个给定元素的所有CSS规则被读取。

Is there a way to select all CSS rules of an element with JavaScript? I'm not looking for a specific solution, just as long as all CSS rules of a given element are read.

所以,我有以下HTML

So, I have the following HTML

<div class='styledDiv' style='height:100px;width:100px;'></div>

,然后在单独的CSS文件中:

and then in a separate CSS file:

.styledDiv
{
  background-color: #ccc;
  border: solid 5px blue;
}



我希望最终结果包括所有内联和单独的文件CSS规则。无论最终结果是什么格式,无论是字符串还是数组,无论如何。

I'd like the final result to include all inline and separate file CSS rules. It doesn't matter in what format the final result is, be it a string or an array, whatever.

让我也提到,我看了一些代码,来自单独的CSS文件的CSS规则。我认为可能有一个更好的解决方案。此外,FireFox和Chrome允许循环通过.style属性,就像循环遍历数组一样。但是,FF向右和左边框/边距/填充输出 - * tl源规则,并且不显示实际的CSS值。解决方案涉及jQuery也很好。

Let me also mention, I looked at some code that reads CSS rules from a separate CSS file. I think there could be a better solution. Also, FireFox and Chrome allow to loop through .style property the same way as looping through an array. However, FF spits out -*tl-source rules for right and left border/margin/padding and doesn't show the actual CSS values. Solution involving jQuery is also fine.

推荐答案

对于FireFox,可以使用: https://developer.mozilla.org/en/DOM:window.getComputedStyle

For FireFox, you can use this: https://developer.mozilla.org/en/DOM:window.getComputedStyle

对于IE,您可以使用:
http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx

For IE, you can use this: http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx

请注意!您在此处跋涉在黑暗的水域。

Be aware! You are treading on dark waters here.

这些结果返回浏览器对CSS的解释。例如,当获取颜色时,IE会返回 HEX颜色代码,而Firefox返回 rbg code 。对于字体大小IE将返回实际的继承的字体大小,而Firefox将返回 pt

These results return the browser's interpretation of CSS. For example, when getting colors, IE would return the HEX color codes while Firefox returns rbg code. And for font sizes IE would return the actual inherited font size while Firefox will return pt based.

这篇关于使用JavaScript获取元素的所有CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆