检索DOM textnode位置

dpq*_*dpq 17 dom textnode

是否可以检索文本节点的几何位置(即父元素,页面等的顶部/左侧偏移)?

bob*_*nce 14

不是直接的.TextNode没有用于测量视口定位的原始IE偏移*(和类似)扩展.

仅在IE上,您可以创建一个TextRange对象,费力地尝试将其与TextNode的边界对齐,然后测量TextRange的boundingLeft/boundingTop,并将其添加到父元素的位置(通过常规方法获得) .然而,这是一个针对可能不稳定的单一浏览器解决方案的大量工作.

您可能能够逃脱的另一种方法是将文本包装在span元素中(在文档中,或者通过脚本动态地和/或临时地),并使用跨度来测量定位,假设它没有拾取任何额外的可能影响位置的样式.但请注意,包裹的跨度可能无法给出预期的右/下值; 根据你想要用它做什么,你最终可能会包装第一个和最后一个字符或其他一些安排.

总结:urgh,没什么好处的.


fre*_*nte 9

今天,您可以通过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);
Run Code Online (Sandbox Code Playgroud)
/* 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}
Run Code Online (Sandbox Code Playgroud)
The red lines will show you the coordinates bounding box of the <strong>selected textnode</strong>.
Run Code Online (Sandbox Code Playgroud)