Get the True Font Family Value in JavaScript
In a previous question, it was discussed how to obtain the font size through JavaScript. Now, we'll explore how to determine the actual font family name from the computed style of a DOM element.
By default, the computed style function only returns the entire font definition, including the full font family stack. However, for selecting fonts in a drop-down menu, we need the exact name of the font in use.
Solution
To extract the true font family name, utilize the following code:
let para = document.querySelector('p'); let compStyles = window.getComputedStyle(para); let computedFontFamily = compStyles.getPropertyValue('font-family');
This will return a string like "Times New Roman", which can be matched against the options in your font family drop-down.
Browser Support
The code above is supported in all major browsers, providing a consistent way to get the computed font family value.
The above is the detailed content of How to Get the True Font Family Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!