检索DOM文本节点位置

21

有没有可能检索文本节点的几何位置(即相对于父元素、页面等的上部/左部偏移量)?

6个回答

14

并非直接地。TextNode没有原始的IE offset*(和类似的)扩展来测量在视口上的定位。

仅在IE上,您可以创建一个TextRange对象,费力地尝试将其与TextNode的边界对齐,然后测量TextRange的boundingLeft / boundingTop,并将其添加到父元素的位置(通过通常的方法获取)。但是,这是为了潜在摇晃的单一浏览器解决方案而进行的大量工作。

另一种方法是,您可以将文本包装在span元素中(无论是在文档中还是通过脚本动态或暂时地),并使用该span来测量定位,假设它没有获取任何可能影响位置的其他样式。但是请注意,包装的span可能无法给出所期望的右/下值;根据您想要执行的操作,您可能会包装第一个和最后一个字符或其他排列。

总之:唉,没什么好办法。


使用了您的想法 - 感谢您的洞见!http://stackoverflow.com/questions/6990350/jquery-get-text-currently-shown-ie-not-just-visible/6990382#6990382 - AlienWebguy
可惜,但将其包装在<span>中会修改页面,对我没有用处。 - SuperUberDuper

11
今天你可以通过 Range.getBoundingClientRect() 来实现。

// 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>.


1
我给了你+1的赞,因为你提供了对我来说最好的答案。我已经验证了这在Chromium中也可以工作。查看https://developer.mozilla.org/en-US/docs/Web/API/Range/getBoundingClientRect,它似乎被广泛支持,因此在我看来,这应该是被选择的答案。 - KevinHJ

2

相对于视口的文本节点

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
  }
}


0

看一下这篇文章 - 它使用offsetParent属性递归地计算偏移量。

我总是建议使用jQuery来处理浏览器差异的问题,像这样的东西。jQuery CSS函数似乎有你需要的方法!


1
很遗憾,DOM文本节点似乎没有offsetLeft / offsetTop属性。而jQuery也不能很好地处理文本节点:我找不到如何为它们编写选择器表达式(别管children()没有返回文本节点)。 - dpq

0

目前还没有内置的跨浏览器方法可以实现这一点。我建议使用带有 Dimensions 插件的 jQuery:http://brandonaaron.net/docs/dimensions/

它是跨浏览器的,可以给你提供高度、宽度、x 和 y 的偏移量等信息。


-1

4
文本节点无法使用客户区矩形。 - Bruno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接