Home >Web Front-end >CSS Tutorial >How Can I Reliably Get an HTML Element's Font Size?
When attempting to retrieve the font size of an element, the initial idea of accessing style.fontSize might prove insufficient. This is particularly true when the font size is defined externally in a stylesheet, resulting in an empty string when retrieved using this method.
To address this, you can utilize window.getComputedStyle, as illustrated below:
var el = document.getElementById('foo'); var style = window.getComputedStyle(el, null).getPropertyValue('font-size'); var fontSize = parseFloat(style); // Convert the style value to a numeric font size el.style.fontSize = (fontSize + 1) + 'px'; // Increment the font size by 1
This approach accurately retrieves the font size, even if it's defined in a stylesheet. The resulting fontSize variable can then be used to dynamically adjust the font size of the specified element.
The above is the detailed content of How Can I Reliably Get an HTML Element's Font Size?. For more information, please follow other related articles on the PHP Chinese website!