是否可以检索文本节点的几何位置(即从父元素、页面等的顶部/左侧偏移量)?
6 回答
不是直接的。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
}
}
看看这篇文章- 它使用 offsetParent 属性递归地计算出偏移量。
我总是推荐 jquery 来滚动你自己的方法来处理像这样的浏览器变化的东西。jquery CSS 函数似乎有你需要的方法!
没有任何内置的跨浏览器方法可以做到这一点。我会将 jQuery 与Dimensions 插件一起使用:http: //brandonaaron.net/docs/dimensions/
它是跨浏览器的,会为您提供高度、宽度和 x & y 偏移量等。
这些天有办法。一种方式:getBoundingRectangle:https ://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect