简体   繁体   English

如何在浏览器中获取字体大小的行高?

[英]How can I get a line height from font size within browser?

Range.getClientRects() method returns a list of ClientRect occupied by range and this works well when the range is within normal span which has text. Range.getClientRects()方法返回由range占用的ClientRect列表,当范围在具有文本的正常范围内时,这种方法很有效。

<div class="line">
  <span class="run">Hello!</span><span class="run"></span>
</div>

But it fails to get ClientRect when span is empty. 但是当span为空时它无法获得ClientRect (like in the second span) (就像在第二个跨度)

I've tried the followings, however, the results were not satisfactory. 我尝试了以下,但结果不尽如人意。

  • Set span's display property to inline-block 将span的display属性设置为inline-block
  • Insert '\' into span. '\'插入span。 In this case, I can get ClientRect but this will mess up the other parts of codes. 在这种情况下,我可以获得ClientRect但这会搞乱代码的其他部分。

If I can compute line height from the font-size , it would be best. 如果我可以从font-size计算行高,那将是最好的。 Is there any way to get the line height of empty span in px? 有没有办法在px中获得空跨度的行高?

NOTE: I'm not trying to get line-height css property. 注意:我不是想获得line-height css属性。 In this case, the line-height would be normal . 在这种情况下, line-height将是normal

You could traverse the DOM tree above the span to find the nearest element with a numerical line-height definition. 您可以遍历跨度上方的DOM树,以查找具有数字行高定义的最近元素。 In my test case this seems to work on percentage line-heights too -- it gets the computed line-height not the percentage. 在我的测试用例中,这似乎也适用于百分比行高 - 它获得计算的行高而不是百分比。 I'm not sure about the cross-browser support on that though. 虽然我不确定跨浏览器的支持。

Demo: http://jsfiddle.net/colllin/DHLWW/ 演示: http//jsfiddle.net/colllin/DHLWW/

Code: 码:

var lineHeight = -1;
var $span = $('span');
var tree = $span.get().concat( $span.parents().get() );
$(tree).each(function(index, element) {
    if (lineHeight < 0) {
        lineHeight = parseFloat($(element).css('line-height')) || -1;
    }
});
$(document.body).append('<br>line-height of span: '+lineHeight);
  1. Just put any character into this <span> . 只需将任何字符放入此<span> In this case, I put a U+FEFF character. 在这种情况下,我放了一个U+FEFF字符。

     var elem = $('span')[0]; elem.textContent = '\'; 
  2. Get a rectangle. 得到一个矩形。

     var rect = elem.getClientRect(); ... 
  3. Restore the <span> to be empty. <span>恢复为空。

     elem.textContent = ''; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM