如何获取跨度的线高?
有没有办法在 JavaScript/jQuery 中获取 span
(或其他内联元素)的 line-height
?
我需要精确计算的行高
(以像素为单位),而不是1.2em
、正常
或启发式排序的值例如fontSize * 1.5
。
我需要做的是拉伸 span
的背景以填充线条的整个高度。我认为我可以添加填充来拉伸跨度,但为此我需要精确的行高。如果有人可以提供另一种方法,这也会有所帮助。
Is there a way to get the line-height
of a span
(or other inline element) in JavaScript/jQuery?
I need the exact computed line-height
in pixels, not values of the sort 1.2em
, normal
or heuristics like fontSize * 1.5
.
What I need to do is stretch the background of a span
to fill the whole height of the line. I figured that I could add paddings to stretch the span, but for this I need the exact line-height
. If someone can offer another approach, this would also be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个简单的方法是:
这将在不使用 jQuery 的情况下获得行高的计算值,并且适用于 IE9 及以上的所有浏览器。
An easy way to do this is:
This will get the calculate value of the line height without using jQuery and works on all browsers from IE9 onwards.
例如,以字符串“16px”形式检索计算出的 px 值。它在幕后使用 IE 的
currentStyle
或标准getCompulatedStyle
。这有点令人惊讶,因为当它作为 setter 工作时,它会执行elem.style.something = value
,这是完全不同的事情。Retrieves the computed px value as a string "16px" for example. It uses IE's
currentStyle
or the standardgetComputedStyle
under the covers. Which is kind of surprising seeing as when it works as a setter it doeselem.style.something = value
which is a whole different thing.假设 span 包含在 div 中。
您可以将 div 设置为position:relative
,并将跨度设置为占据 100% 高度的块。
通过这种方式,您可以根据需要拉伸跨度。
示例此处
(注意:要查看效果,请将span的背景颜色更改为透明。您应该能够看到红色的div。)
assuming that the span is contained in a div.
you could set the div to position:relative
and the span as a block that takes 100% height.
In this way you will stretch the span as you want.
Example here
(note: to see the effect, change the background colour of the span to transparent. You should be able to see the red div.)
如果您的设计允许,您可以将 inline-block 应用于您的目标元素,然后使用
outerHeight
...If your design allows for it, you can apply inline-block to the elements you are targeting and then use
outerHeight
...