javascript 如何获取文本的真实高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15161385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the real height of a text?
提问by ettolo
Referring go this example
http://jsfiddle.net/uzgJX/
参考这个例子
http://jsfiddle.net/uzgJX/
The result is the height of the box containing the text (the one you can see if you select the text with the mouse..) wichi is higher then the real height of the text.
Is there a way to get the real height with jquery or plain js?
In the example I tryed with
结果是包含文本的框的高度(如果您用鼠标选择文本,您可以看到的高度..) wichi 高于文本的实际高度。
有没有办法用 jquery 或普通 js 获得真实高度?
在我尝试的例子中
text.height()
and
和
text[0].getBoundingClientRect().height
with no luck, it says 19px instead of 14px
运气不好,它说 19px 而不是 14px
采纳答案by Andy E
Get the computed font-size
for your text element instead:
获取font-size
文本元素的计算结果:
parseInt(window.getComputedStyle(text[0]).fontSize, 10);
font-size
represents the size of an em square for a font. It should be noted that, while most glyphs will stay inside the bounds of an em square, some mayexceed those bounds. This doesn't usually occur on the vertical dimentions, though.
font-size
表示字体的 em 正方形的大小。应该注意的是,虽然大多数字形会停留在 em 方格的边界内,但有些可能会超出这些边界。不过,这通常不会发生在垂直维度上。
Give it a try: http://jsfiddle.net/uzgJX/1/. Tip: screenshot and copy into your favourite image editor, then select the pixels exactly to the height of the text and compare with the value given in the fiddle.
试一试:http: //jsfiddle.net/uzgJX/1/。提示:截图并复制到您最喜欢的图像编辑器中,然后选择与文本高度完全相同的像素,并与小提琴中给出的值进行比较。