Home >Web Front-end >CSS Tutorial >How to Determine the Actual Computed Font-Family Name in JavaScript?

How to Determine the Actual Computed Font-Family Name in JavaScript?

DDD
DDDOriginal
2024-10-24 06:28:021035browse

How to Determine the Actual Computed Font-Family Name in JavaScript?

Determining the Computed Font-Family Name in JavaScript

In a previous thread, the issue of accurately retrieving the computed font size was successfully resolved. However, challenges persist in acquiring the actual font name, particularly given that the generic computed style function merely provides the complete font string.

To ensure compatibility with font family dropdown menus, we require the precise font name of the element. Is there a reliable method to achieve this, especially for widely used web fonts?

Solution

To obtain the computed font-family using JavaScript from the DOM, follow these steps:

<code class="javascript">let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
let computedFontFamily = compStyles.getPropertyValue('font-family'); // e.g. "Times New Roman"</code>

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

The above is the detailed content of How to Determine the Actual Computed Font-Family Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn