使用以下方法:
遍历
CSSStyleDeclaration
对象的索引(getComputedStyle)以获取每个已知的属性名称。使用getPropertyValue
+这个名称来获取值。
代码优化:不要getComputedStyle
用于每次迭代,而是将其存储在循环外部的变量中。对使用普通
for ( name in object )
循环currentStyle
。- 对内联样式使用相同的循环方法
码:
function getStyleById(id) { return getAllStyles(document.getElementById(id));}function getAllStyles(elem) { if (!elem) return []; // Element does not exist, empty list. var win = document.defaultView || window, style, styleNode = []; if (win.getComputedStyle) { style = win.getComputedStyle(elem, ''); for (var i=0; i<style.length; i++) { styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) ); // ^name ^^ value ^ } } else if (elem.currentStyle) { style = elem.currentStyle; for (var name in style) { styleNode.push( name + ':' + style[name] ); } } else { style = elem.style; for (var i=0; i<style.length; i++) { styleNode.push( style[i] + ':' + style[style[i]] ); } } return styleNode;}


