4

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.

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

But it fails to get ClientRect when span is empty. (like in the second span)

I've tried the followings, however, the results were not satisfactory.

  • Set span's display property to inline-block
  • Insert '\ufeff' into span. In this case, I can get ClientRect but this will mess up the other parts of codes.

If I can compute line height from the font-size, it would be best. Is there any way to get the line height of empty span in px?

NOTE: I'm not trying to get line-height css property. In this case, the line-height would be normal.

ntalbs
  • 28,700
  • 8
  • 66
  • 83
  • What other parts of your codes get messed up? Can you just undo your changes immediately after you get the value? – colllin Feb 27 '14 at 06:36
  • You can't compute line-height from font-size -- it's both browser dependent and font-family dependent. Sorry for the super unhelpful "answer" :) – colllin Feb 27 '14 at 06:37
  • I expected formula that compute line height from font size. Now I understand that it depends on both browser and font-family, which means it can't be calculated from a simple formula. Thank you for your comment and interest. – ntalbs Feb 27 '14 at 09:11

2 Answers2

1

You could traverse the DOM tree above the span to find the nearest element with a numerical line-height definition. 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/

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);
colllin
  • 9,442
  • 9
  • 49
  • 65
  • The idea of getting the height of parent element is good. However, it doesn't solve the problem completely. Consider that the div contains two spans which have different font size, respectively. – – ntalbs Feb 27 '14 at 08:02
1
  1. Just put any character into this <span>. In this case, I put a U+FEFF character.

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

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

    elem.textContent = '';
    
SJ Baek
  • 138
  • 1
  • 6