使用javascript打印HTML元素的内嵌样式值
如何打印使用javascript的html元素的样式属性值。我可以用document.getElementById('myId').style.property
的特定样式属性值,其中property
是一样的东西width
,height
等使用javascript打印HTML元素的内嵌样式值
但是,我怎么能得到的样式元素的整个列表?
document.getElementById('myId').style.cssText
为字符串,或document.getElementById('myId').style
为对象。
编辑:
据我所知,这将返回“实际”,内联样式。关于元素<a id='myId' style='font-size:inherit;'>
,document.getElementById('myId').style.cssText
应返回"font-size:inherit;"
。如果这不是你想要的,请尝试document.defaultView.getComputedStyle
或document.getElementById('myId').currentStyle
(第一个是IE除外,第二个仅限于IE)。有关计算与级联样式的更多信息,请参阅here。
其实我需要它作为一个字符串,感谢您的帮助.. –
<div id="x" style="font-size:15px">a</div>
<script type="text/javascript">
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
// get what style rule you want
alert(getStyle(document.getElementById('x'), 'font-size'));
</script>
IE 9中支持document.defaultView –
不,它不是,但''currentStyle' '是 –
如果你想要一个元素的风格**属性的值**(即“inline”风格),那么唯一的方法就是* getAttribute *(这在某些浏览器中是很麻烦的,所以不太可靠)。但是,如果您想要HTML元素的样式对象的各种**属性的值**,则下面的答案可能会有所帮助。 – RobG