是否可以使用JavaScript获取对象的所有样式?就像是:
main.css ------- #myLayer { position: absolute; width: 200px; height: 100px; color: #0000ff; } main.js ------- var ob = document.getElementById("myLayer"); var pos = ob.(getPosition); // Pos should equal "absolute" but // ob.style.position would equal null // any way to get absolute?
在上一篇文章中,这是一个函数:
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; }
如何使用它:
CSS:
/* Element CSS*/ div#container{ font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif; }
JS:
var elementFontSize = getStyle(document.getElementById("container"), "font-size");