Printing inline style values of an HTML element using javascript
How can i print the value of style attribute of an html element using javascript. I can get a specific style property value using document.getElementById('myId').style.property
, where property开发者_如何学C
is something like width
, height
etc.
However, how can I get the entire list of styles for an element?
document.getElementById('myId').style.cssText
as a String, or document.getElementById('myId').style
as an Object.
Edit:
As far as I can tell, this returns the "actual", inline style. On the element <a id='myId' style='font-size:inherit;'>
, document.getElementById('myId').style.cssText
should return "font-size:inherit;"
. If that is not what you want, try document.defaultView.getComputedStyle
or document.getElementById('myId').currentStyle
(the first one is all except IE, the second one is IE only). See here for more on computed vs. cascaded styles.
<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>
Oh srsly... it's as easy as
element.style.cssText
and it's cross browser
http://jsfiddle.net/4F2RQ/
This should do a dump of the object: Here's an Example
EDIT: Its a little weird:
for (var prop in styles) {
console.log(styles[prop], styles[styles[prop]]);
}
精彩评论