2011-09-06 78 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' '是 –

相關問題