Get computed font size for DOM element in JS

て烟熏妆下的殇ゞ 提交于 2019-11-26 15:19:59

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)]; 
  }
}

Usage:

var element = document.getElementById('elementId');
getStyle(element, 'font-size');

More info:

Edit: Thanks to @Crescent Fresh, @kangax and @Pekka for the comments.

Changes:

  • Added camelize function, since properties containing hypens, like font-size, must be accessed as camelCase (eg.: fontSize) on the currentStyle IE object.
  • Checking the existence of document.defaultView before accessing getComputedStyle.
  • Added last case, when el.currentStyle and getComputedStyle are not available, get the inline CSS property via element.style.

To overcome the 'em' problem I have quickly written a function, if the font-size in ie is 'em' the function calculates with the body font-size.

        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;
    }

Looks like jQuery (1.9 at least) uses getComputedStyle() or currentStyle itself when you use $('#element')[.css][1]('fontSize'), so you really shouldn't have to bother with more complicated solutions if you're OK using jQuery.

Tested in IE 7-10, FF and Chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!