Home >Web Front-end >CSS Tutorial >How to Retrieve a Specific Font-Family Name using Computed Styles in JavaScript?
As an extension to a previous inquiry, the challenge of addressing cross-browser font-family determination arises. While determining font size has been resolved, identifying the precise font-family poses additional difficulties.
The current implementation extracts only the complete font string, which may comprise stacked alternatives like "Times New Roman, Georgia, Serif." To match the font drop-down menu settings, however, we seek a fixed font name representing the actual font employed by the DOM element under scrutiny.
Leveraging the powerful getComputedStyle() method, we can retrieve the computed font-family in a manner compatible with most major browsers:
<code class="js">let paragraph = document.querySelector('p'); let computedStyle = window.getComputedStyle(paragraph); let fontfamily = computedStyle.getPropertyValue('font-family'); // e.g. "Times New Roman"</code>
This approach ensures that the font-family retrieved accurately reflects the font currently rendered on the DOM element, enabling seamless font drop-down menu alignment.
The above is the detailed content of How to Retrieve a Specific Font-Family Name using Computed Styles in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!