如何获得文本的真实高度?

时间:2022-11-08 15:22:50

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

1 个解决方案

#1


12  

Get the computed font-size for your text element instead:

获取文本元素的计算字体大小:

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 may exceed 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/。提示:截图并复制到您喜欢的图像编辑器中,然后选择与文本高度完全相同的像素,并与小提琴中给出的值进行比较。

#1


12  

Get the computed font-size for your text element instead:

获取文本元素的计算字体大小:

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 may exceed 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/。提示:截图并复制到您喜欢的图像编辑器中,然后选择与文本高度完全相同的像素,并与小提琴中给出的值进行比较。