开发者

How to get the actual rendered font when it's not defined in CSS?

开发者 https://www.devze.com 2023-04-05 13:33 出处:网络
How do I get the actual font face and font size of an element when the CSS font-face and font-size prop开发者_如何学Pythonerties are not defined?

How do I get the actual font face and font size of an element when the CSS font-face and font-size prop开发者_如何学Pythonerties are not defined?

For example, the JavaScript snippet

object.style.fontFamily

does not return any value. That's pretty obvious, assuming CSS hasn't applied a style to object anywhere. But, of course, a certain font is used to render the text, probably the system font or the webbrowser default font.

So can, for instance, JavaScript get that rendered font?


I suggest this function:

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

Usage:

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

Note: getComputedStyle doesn't work in IE8.

Live demo: http://jsfiddle.net/4mxzE/

console.log(
  getComputedStyle(document.getElementById('test'), null)
    .getPropertyValue('font')
)
#test {
  font-family: fantasy, cursive;
}
<div id="test">Lorem ipsum dolor sit font-face</div>


There is no standard, reliable method for determining the actual font being used. The previous answers here will report the styled fontFamily style value, but that can be a list of font names and doesn't specifically identify the actual font rendered (which was the actual question posed here).

(As mentioned in some comments, there are ways to guess at the font by inspecting visual cues, but that isn’t likely to be 100% reliable.)


You can find the information about the rendered font in Chrome/Firefox Developer Tools. Try inspecting the paragraph in the following code snippet:

p { font-family: sans-serif;  }
<p>Some text and <span title="an emoji">
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号