在Javascript中测量文本节点的边界框 [英] Measure bounding box of text node in Javascript
问题描述
我无法使用Javascript获取文本节点的大小(以像素为单位)。示例:
I'm having trouble getting the size, in pixels, of a text node using Javascript. Example:
<p>
first text block
<b>second text block</b>
</p>
我需要独立获取两个文本块的边界框。我可以通过测量< b>元素来获得第二个块的大小,但第一个块让我望而却步。据我所知,Javascript中的文本节点似乎没有高度或宽度。
I need to get the bounding box of the two text blocks independently. I could get the size of the second block just by measuring the <b> element, but the first one eludes me. It doesn't appear that textnodes in Javascript have a height or width, so far as I can tell.
在< span>中包装第一个文本块并进行测量这不是一个选项,因为我发现一个span不一定继承它上面的所有样式,当我包装文本时它会突然改变大小。这就像Javascript的海森堡不确定性原则;我尝试测量某些东西会改变它。
Wrapping the first text block in a <span> and measuring that is not an option, because I've discovered that a span does not necessarily inherit all of the styles above it, and when I wrap the text it suddenly changes size. It's like the Heisenberg Uncertainty Principle of Javascript; my attempt to measure something changes it.
我正在构建一个将HTML分解为页面的应用程序(实际上是EPUB HTML),我需要知道位置,高度,以及页面上每个文本块的宽度,以便我知道是将它放在此页面还是下一页。
I'm building an app that breaks HTML into pages (EPUB HTML, actually), and I need to know the position, height, and width of each block of text on the page so I can know whether to put it on this page or the next page.
有任何建议吗?
推荐答案
你可以用支持范围来做到这一点/www.w3.org/TR/cssom-view/#extensions-to-the-range-interfacerel =noreferrer> CSSOM查看扩展程序,这是最新的浏览器(Firefox 4 +,WebKit自在2009年初,Opera 11,可能更早)和IE中的 TextRange
。 TextRange
代码很乏味,所以我在这里省略了它。
You can do this with a Range
that supports CSSOM View extensions, which is most recent browsers (Firefox 4+, WebKit since early 2009, Opera 11, maybe earlier) and a TextRange
in IE. The TextRange
code is tedious, so I've omitted it here.
jsFiddle: http://jsfiddle.net/gdn6C/1/
jsFiddle: http://jsfiddle.net/gdn6C/1/
代码:
function getTextNodeHeight(textNode) {
var height = 0;
if (document.createRange) {
var range = document.createRange();
range.selectNodeContents(textNode);
if (range.getBoundingClientRect) {
var rect = range.getBoundingClientRect();
if (rect) {
height = rect.bottom - rect.top;
}
}
}
return height;
}
这篇关于在Javascript中测量文本节点的边界框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!