获取JS中DOM元素的计算字体大小 [英] Get computed font size for DOM element in JS
问题描述
可以检测DOM元素的计算 font-size
,同时考虑其他地方进行的通用设置(在 body
tag),继承的值,等等?
Is it possible to detect the computed font-size
of a DOM element, taking into consideration generic settings made elsewhere (In the body
tag for example), inherited values, and so on?
一个框架独立的方法将是很好的,因为我正在一个脚本,应该独立工作,但这不是一个要求。
A framework-independent approach would be nice, as I'm working on a script that should work standalone, but that is not a requirement of course.
背景:我试图调整 CKEditor 的字体选择器插件(来源此处),以便它始终显示当前光标位置的字体大小(与仅在具有显式 font-size
设置的 span
,这是当前的行为)。
Background: I'm trying to tweak CKEditor's font selector plugin (source here) so that it always shows the font size of the current cursor position (as opposed to only when within a span
that has an explicit font-size
set, which is the current behaviour).
推荐答案
您可以尝试使用非标准IE element.currentStyle
属性,否则您可以查找 DOM Level 2 标准 getComputedStyle
方法(如果有):
You could try to use the non-standard IE element.currentStyle
property, otherwise you can look for the DOM Level 2 standard getComputedStyle
method if available :
function getStyle(el,styleProp) {
var camelize = function (str) {
return str.replace(/\-(\w)/g, function(str, letter){
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
用法:
var element = document.getElementById('elementId');
getStyle(element, 'font-size');
更多信息:
- 获取样式(QuirksMode)
- Get Styles (QuirksMode)
编辑:感谢 @Crescent Fresh , @kangax
更改:
- code> camelize 函数,因为包含连字符的属性,如
font-size
必须作为camelCase访问(例如:<$ cc> currentStyle IE对象。 - 检查<$ c $
- 添加上一个案例,当
时,
和c> document.defaultView > el.currentStyle getComputedStyle
不可用,通过element.style获取内联CSS属性
。
- Added
camelize
function, since properties containing hypens, likefont-size
, must be accessed as camelCase (eg.:fontSize
) on thecurrentStyle
IE object. - Checking the existence of
document.defaultView
before accessinggetComputedStyle
. - Added last case, when
el.currentStyle
andgetComputedStyle
are not available, get the inline CSS property viaelement.style
.
这篇关于获取JS中DOM元素的计算字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!