[英]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. 我尝试了以下,但结果不尽如人意。
inline-block
inline-block
'\'
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);
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 = '\';
Get a rectangle. 得到一个矩形。
var rect = elem.getClientRect(); ...
Restore the <span>
to be empty. 将
<span>
恢复为空。
elem.textContent = '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.