【发布时间】:2010-09-28 15:21:58
【问题描述】:
是否可以检索文本节点的几何位置(即从父元素、页面等的顶部/左侧偏移量)?
【问题讨论】:
是否可以检索文本节点的几何位置(即从父元素、页面等的顶部/左侧偏移量)?
【问题讨论】:
不直接。 TextNode 没有用于测量视口定位的原始 IE 偏移*(和类似的)扩展。
仅在 IE 上,您可以创建一个 TextRange 对象,费力地尝试将其与 TextNode 的边界对齐,然后测量 TextRange 的 boundingLeft/boundingTop,并将其添加到父元素的位置(由通常的意思)。然而,对于一个可能不稳定的单浏览器解决方案来说,这是一大堆工作。
另一种您可能能够摆脱的方法是将文本包装在 span 元素中(在文档中,或通过脚本动态和/或临时地),并使用 span 来测量定位,假设它没有选择可能影响位置的任何其他样式。但是请注意,包裹的跨度可能不会给出预期的右/底部值;根据你想用它做什么,你最终可能会包装第一个和最后一个字符或其他一些排列。
总而言之:呃,没什么好说的。
【讨论】:
今天您可以通过Range.getBoundingClientRect()。 IE9+
// Get your text node
const el = document.querySelector('strong')
const textNode = el.firstChild;
// Get coordinates via Range
const range = document.createRange();
range.selectNode(textNode);
const coordinates = range.getBoundingClientRect()
console.log(coordinates);
/* Demo CSS, ignore, highlights box coordinates */ body{max-width:300px}strong{position:relative}strong,strong:before{border:solid 1px red}strong:before{content:'';position:absolute;right:100%;bottom:100%;width:100vw;height:100vh;pointer-events:none}
The red lines will show you the coordinates bounding box of the <strong>selected textnode</strong>.
【讨论】:
相对于视口的文本节点
function getBoundingClientRectText(textNode) {
const range = document.createRange()
range.selectNode(textNode)
return range.getBoundingClientRect()
}
相对于元素的文本节点
function getTextOffsetRelativeToElement(element, textNode) {
const elementRect = element.getBoundingClientRect()
const range = document.createRange()
range.selectNode(textNode)
const textRect = range.getBoundingClientRect()
return {
top: textRect.top - elementRect.top,
left: textRect.left - elementRect.left
}
}
相对于文本节点父元素的字符偏移量
function getCharOffset(textNode, offset) {
const parentRect = textNode.parentElement.getBoundingClientRect()
const range = document.createRange()
range.setStart(textNode, offset)
range.setEnd(textNode, offset + 1)
const charRect = range.getBoundingClientRect()
return {
top: charRect.top - parentRect.top,
left: charRect.left - parentRect.left
}
}
【讨论】:
看看this article - 它使用 offsetParent 属性递归地计算出偏移量。
我总是推荐 jquery 而不是滚动你自己的方法来处理像这样的浏览器变化的东西。 jquery CSS functions 好像有你需要的方法!
【讨论】:
没有任何内置的跨浏览器方法可以做到这一点。我会 将 jQuery 与Dimensions 插件一起使用:http://brandonaaron.net/docs/dimensions/
它是跨浏览器的,可以为您提供高度、宽度和 x 和 y 偏移等。
【讨论】:
现在有办法。一种方式:getBoundingRectangle:https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
【讨论】: