Equivalent to bfavaretto but with compatibility for legacy browsers:
function getStyle(elem, prop)
{
if (elem.currentStyle) { //IE8
prop = prop.replace(/-([a-z])/gi, function (value) {
return value.toLowerCase();
});
return elem.currentStyle[prop];
} else if (window.getComputedStyle) {//Navegadores modernos
prop = prop.replace(/([A-Z])/g, '-$1').toLowerCase();
return window.getComputedStyle(elem, null).getPropertyValue(prop);
}
}
console.log(getStyle(document.getElementById('Teste'), 'font-size'));
console.log(getStyle(document.getElementById('Teste'), 'fontSize'));
html {font: normal 16px / 25px 'Montserrat';}
<p id="Teste">Foo bar</p>
Extra
Even using jQuery.css or getStyle there is a very important detail, in different browsers can occur not returning in pixels (% with%), can return values as px
or em
.
To remove these characters I recommend using pt
with regex and do not use .replace
without checking if the value is parseInt
or something else (as empty), otherwise it can give problem, do so:
tamanhoFonte = $(elemento).css('font-size'); //ou getStyle(elemento, 'font-size')
tamanhoFonte = tamanhoFonte.replace(/[a-z]/gi, ""); //Remove letras, mas mantem pontos e numeros
tamanhoFonte = tamanhoFonte ? parseInt(tamanhoFonte) : 0;