使用javascript打印HTML元素的内联样式值

Printing inline style values of an HTML element using javascript

本文关键字:样式 元素 javascript 打印 HTML 使用      更新时间:2023-09-26

如何使用javascript打印html元素的style属性的值。我可以使用document.getElementById('myId').style.property获得特定的样式属性值,其中propertywidth, height等。

但是,我如何获得一个元素的整个样式列表呢?

document.getElementById('myId').style.cssText作为String,或document.getElementById('myId').style作为Object。

编辑:

据我所知,这将返回"实际的"内联样式。对于元素<a id='myId' style='font-size:inherit;'>, document.getElementById('myId').style.cssText应该返回"font-size:inherit;"。如果这不是您想要的,请尝试document.defaultView.getComputedStyledocument.getElementById('myId').currentStyle(第一个是除IE之外的所有,第二个是IE)。有关计算样式和级联样式的更多信息,请参阅此处。

<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>

哎呀…就像

一样简单
element.style.cssText

和跨浏览器

http://jsfiddle.net/4F2RQ/

这应该会转储对象:下面是一个示例

编辑:这有点奇怪:

for (var prop in styles) {
    console.log(styles[prop], styles[styles[prop]]);
}