未在 CSS 中定义时如何获取实际呈现的字体? [英] How to get the actual rendered font when it's not defined in CSS?
问题描述
当 CSS font-face
和 font-size
属性未定义时,如何获取元素的实际字体和字体大小?
How do I get the actual font face and font size of an element when the CSS font-face
and font-size
properties are not defined?
例如,JavaScript 代码段
For example, the JavaScript snippet
object.style.fontFamily
不返回任何值.这很明显,假设 CSS 没有将样式应用于 object
的任何地方.但是,当然,使用某种字体来呈现文本,可能是系统字体或浏览器默认字体.
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.
例如,JavaScript 可以获取渲染的字体吗?
So can, for instance, JavaScript get that rendered font?
推荐答案
我建议使用这个功能:
function css( element, property ) {
return window.getComputedStyle( element, null ).getPropertyValue( property );
}
用法:
css( object, 'font-size' ) // returns '16px' for instance
注意:getComputedStyle
在 IE8 中不起作用.
Note: getComputedStyle
doesn't work in IE8.
现场演示: http://jsfiddle.net/4mxzE/
这篇关于未在 CSS 中定义时如何获取实际呈现的字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!