Home >Web Front-end >CSS Tutorial >How Can I Get the Actual Rendered Font in JavaScript When CSS Font Properties Are Undefined?

How Can I Get the Actual Rendered Font in JavaScript When CSS Font Properties Are Undefined?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 07:32:09222browse

How Can I Get the Actual Rendered Font in JavaScript When CSS Font Properties Are Undefined?

Accessing Actual Rendered Font when Undefined in CSS

When accessing the font properties of an element, the JavaScript object.style.fontFamily and object.style.fontSize may return empty values if the corresponding CSS properties are not explicitly set. However, this does not mean that the element is being rendered without a font. The browser typically applies default or inherited styles, which define the actual rendered font.

To retrieve the rendered font information, you can use the getComputedStyle method:

function css(element, property) {
    return window.getComputedStyle(element, null).getPropertyValue(property);
}

For instance:

css(object, 'font-size') // returns '16px'

This method returns the computed value of the specified property, even if it was not explicitly set in the CSS.

Note: getComputedStyle is not supported in IE8.

Live Demo:

[https://jsfiddle.net/4mxzE/](https://jsfiddle.net/4mxzE/)

The above is the detailed content of How Can I Get the Actual Rendered Font in JavaScript When CSS Font Properties Are Undefined?. 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