有没有可能检索文本节点的几何位置(即相对于父元素、页面等的上部/左部偏移量)?
并非直接地。TextNode没有原始的IE offset*(和类似的)扩展来测量在视口上的定位。
仅在IE上,您可以创建一个TextRange对象,费力地尝试将其与TextNode的边界对齐,然后测量TextRange的boundingLeft / boundingTop,并将其添加到父元素的位置(通过通常的方法获取)。但是,这是为了潜在摇晃的单一浏览器解决方案而进行的大量工作。
另一种方法是,您可以将文本包装在span元素中(无论是在文档中还是通过脚本动态或暂时地),并使用该span来测量定位,假设它没有获取任何可能影响位置的其他样式。但是请注意,包装的span可能无法给出所期望的右/下值;根据您想要执行的操作,您可能会包装第一个和最后一个字符或其他排列。
总之:唉,没什么好办法。
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>.
相对于视口的文本节点
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
}
}
看一下这篇文章 - 它使用offsetParent属性递归地计算偏移量。
我总是建议使用jQuery来处理浏览器差异的问题,像这样的东西。jQuery CSS函数似乎有你需要的方法!
目前还没有内置的跨浏览器方法可以实现这一点。我建议使用带有 Dimensions 插件的 jQuery:http://brandonaaron.net/docs/dimensions/
它是跨浏览器的,可以给你提供高度、宽度、x 和 y 的偏移量等信息。
现在有很多方法可以做到。其中一种方式是:getBoundingRectangle: https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect