在JS中获取DOM元素的计算字体大小

37

是否有可能检测DOM元素的计算font-size,考虑到其他地方的通用设置(例如在标签中),继承值等等?

一个独立于框架的方法将是不错的选择,因为我正在编写一个应该能够独立工作的脚本,但这并不是必需的。

背景:我正在尝试调整CKEditor的字体选择插件(源代码在此),使其始终显示当前光标位置的字体大小(而不仅仅是在具有显式font-size设置的内时,这是目前的行为)。


“Computed” 的意思是以像素为单位的尺寸大小? - Crescent Fresh
对于当前情况:仅限像素,但通常能够获取定义值(px、pt、em)和像素值将非常好。 - Pekka
1
@Pekka: 如果只涉及像素,那么你就没问题了。ptem等单位会很难处理,只有IE的currentStyle可以正确获取它们。 - Crescent Fresh
3个回答

60

你可以尝试使用非标准的 IE element.currentStyle 属性,或者寻找标准的 DOM Level 2 中的 getComputedStyle 方法(如果可用):

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');

更多信息:

编辑:感谢@Crescent Fresh@kangax@Pekka的评论。

变更:

  • 添加了camelize函数,因为包含连字符的属性,如font-size,必须在currentStyle IE对象上以驼峰命名方式访问(例如:fontSize)。
  • 在访问getComputedStyle之前检查document.defaultView是否存在。
  • el.currentStylegetComputedStyle不可用时,通过element.style获取内联CSS属性的最后一种情况。

这看起来很不错,我会试一下。 - Pekka
6
注意,currentStylegetComputedStyle 本质上是不同的:http://erik.eae.net/archives/2007/07/27/18.54.15/ getComputedStyle 无法获取继承的样式,而总是将其计算为 px,无论该值是否被声明为 px - Crescent Fresh
6
实际上应该使用document.defaultView.getComputedStyle而非window.getComputedStyle(MDC的错误,或仅考虑了其自己 - Mozilla的实现)。getComputedStyle被指定为AbstractView的成员,而document.defaultView实现了它,并不能保证window == document.defaultView(无论是在规范中还是在实践中都不是这样,实际上Safari 2.x就是window!= document.defaultView的一个很好的例子)。有趣的是,您链接到的getstyles文章中的PPK也犯了类似的错误(在window上测试defaultView)。 - kangax
2
排好序了。@CMS,如果我没记错的话,你需要编辑你的答案,指出currentStyle只接受驼峰式属性(例如fontSize),而getPropertyValue则使用原始形式(font-size)。 - Pekka
在访问getComputedStyle之前,检查document.defaultView的存在也是一个好主意。 - kangax
显示剩余5条评论

4

看起来 jQuery (至少1.9版本) 在使用 $('#element')[.css][1]('fontSize') 时,本身就使用了 getComputedStyle()currentStyle。因此,如果您使用jQuery,则不需要烦恼更复杂的解决方案。

在IE 7-10,火狐和谷歌浏览器中测试通过。


1
或者更简单地说:$('mySelector').css('font-size') - Stephan

2
为了解决“em”问题,我快速编写了一个函数。如果IE中的字体大小是“em”,则该函数会使用正文字体大小进行计算。
        function getFontSize(element){
        var size = computedStyle(element, 'font-size');
        if(size.indexOf('em') > -1){
            var defFont = computedStyle(document.body, 'font-size');
            if(defFont.indexOf('pt') > -1){
                defFont = Math.round(parseInt(defFont)*96/72);
            }else{
                defFont = parseInt(defFont);
            }
            size = Math.round(defFont * parseFloat(size));
        } 
        else if(size.indexOf('pt') > -1){
            size = Math.round(parseInt(size)*96/72)
        }
        return parseInt(size);
    }

    function computedStyle(element, property){
        var s = false;
        if(element.currentStyle){
            var p = property.split('-');
            var str = new String('');
            for(i in p){
                str += (i > 0)?(p[i].substr(0, 1).toUpperCase() + p[i].substr(1)):p[i];
            }
            s = element.currentStyle[str];
        }else if(window.getComputedStyle){
            s = window.getComputedStyle(element, null).getPropertyValue(property);
        }
        return s;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接