2011-09-06 31 views
3

如何打印使用javascript的html元素的样式属性值。我可以用document.getElementById('myId').style.property的特定样式属性值,其中property是一样的东西widthheight使用javascript打印HTML元素的内嵌样式值

但是,我怎么能得到的样式元素的整个列表?

+0

如果你想要一个元素的风格**属性的值**(即“inline”风格),那么唯一的方法就是* getAttribute *(这在某些浏览器中是很麻烦的,所以不太可靠)。但是,如果您想要HTML元素的样式对象的各种**属性的值**,则下面的答案可能会有所帮助。 – RobG

回答

2

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.getComputedStyledocument.getElementById('myId').currentStyle(第一个是IE除外,第二个仅限于IE)。有关计算与级联样式的更多信息,请参阅here

+0

其实我需要它作为一个字符串,感谢您的帮助.. –

1

这应该做对象的转储: 下面是一个Example

编辑:它有点怪异:

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

我以为同样的事情;但不幸的是,这是行不通的。 – NT3RP

+1

什么是控制台对象? –

+0

https://developer.mozilla.org/zh/Using_the_Web_Console – Joe

1
<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> 
+0

IE 9中支持document.defaultView –

+0

不,它不是,但''currentStyle' '是 –

相关问题