Home >Web Front-end >CSS Tutorial >How to Get a DOM Element\'s Computed Font Size in JavaScript?
Understanding the computed font-size of a DOM element is crucial, especially when manipulating elements with complex style inheritance. Here's how you can retrieve this information:
If you have access to Internet Explorer's non-standard element.currentStyle property, you can use this simple code:
if (el.currentStyle) { return el.currentStyle['fontSize']; }
For other browsers that support the DOM Level 2 standard, you can utilize the getComputedStyle method:
if (document.defaultView && document.defaultView.getComputedStyle) { return document.defaultView.getComputedStyle(el, null).getPropertyValue('font-size'); }
As a fallback, if neither currentStyle nor getComputedStyle are available, you can still access the inline CSS property using element.style:
else { return el.style['fontSize']; }
This function can be used as follows:
var element = document.getElementById('elementId'); var fontSize = getStyle(element, 'font-size');
The above is the detailed content of How to Get a DOM Element\'s Computed Font Size in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!