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

发布于 2024-08-15 16:24:06 字数 439 浏览 3 评论 0原文

是否可以检测 DOM 元素的计算 font-size,同时考虑其他地方所做的通用设置(例如在 body 标签中)、继承值等在?

独立于框架的方法会很好,因为我正在开发一个应该独立工作的脚本,但这当然不是必需的。

背景:我正在尝试调整CKEditor的字体选择器插件(来源此处),以便它始终显示当前光标位置的字体大小(而不是仅在在具有显式 font-size 设置的 span 内,这是当前的行为)。

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.

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一花一树开 2024-08-22 16:24:06

您可以尝试使用非标准 IE 元素.currentStyle 属性,否则您可以查找 DOM 级别 2 标准 getCompulatedStyle 方法(如果可用):

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)必须以驼峰命名法(例如:fontSize)在currentStyle IE 对象。
  • 在访问 getCompulatedStyle 之前检查 document.defaultView 是否存在。
  • 添加了最后一种情况,当 el.currentStylegetCompulatedStyle 不可用时,通过 element.style 获取内联 CSS 属性。

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.
七七 2024-08-22 16:24:06

当您使用 $('#element')[.css][1]( 时,jQuery(至少 1.9)使用 getCompulatedStyle()currentStyle 本身'fontSize'),所以如果您可以使用 jQuery,那么您真的不必费心使用更复杂的解决方案。

在 IE 7-10、FF 和 Chrome 中测试

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

海拔太高太耀眼 2024-08-22 16:24:06

为了克服“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;
    }

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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文