是否有一种非天真的方法可以从 DOM 偏移量计算逻辑偏移量?

Is there a non-naïve way of calculating a logical offset from a DOM offset?

我有 highlighted some of the text inside my parent element by placing it in <span>s, and now want to work out what part of it is selected. I have retrieved the Selection 个对象,但它不包含直接有用的信息。我想获得相对于文本开头的偏移量,但它们是相对于突出显示 <span>s 内的文本节点 并且不与parent.textContent.

给定:

有没有比天真的 "explore the tree with a cumulative count" 技术更有效的方法来假装 <span> 不存在以测量 Selection 焦点和锚点?

我不知道它在性能方面是否更有效,您必须对其进行衡量。就代码行而言,Range API 应该使事情变得相当简单。构造从父元素开始到选择开始的范围,然后计算其中包含的字符。

毕竟,Selection 主要是范围的集合。