How to get line height from font size in browser?

Range.getClientRects()returns a ClientRectbusy list , rangeand this works well when the range is within the normal range that the text has.

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

But it does not receive ClientRectwhen the pool is empty. (as in the second flight)

I tried the following, but the results were unsatisfactory.

  • Set the span property value for inline-block
  • Paste '\ufeff'into the span. In this case, I can get ClientRect, but it will ruin the rest of the code.

If I can calculate the row height from font-size, it would be better. Is there a way to get the row height of an empty spacing in px?

NOTE. I am not trying to get the line-heightcss property . In this case there line-heightwill be normal.

+4
source share
2 answers
  • Just put any character on this one <span>. In this case, I put the character U+FEFF.

    var elem = $('span')[0];
    elem.textContent = '\ufeff';
    
  • Get the rectangle.

    var rect = elem.getClientRect();
    ...
    
  • Restore <span>to be empty.

    elem.textContent = '';
    
+1
source

You can cross the DOM tree above the span to find the closest element with a numerical determination of the line height. In my test case, this seems to work on percentage lines too - it calculates linear height, not percentage. However, I'm not sure about cross-browser support.

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

the 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
source

Source: https://habr.com/ru/post/1529141/


All Articles