获取开始和结束偏移值的范围,而不考虑其直接父级



我在p标签内有两个span元素。在该p中选择一些文本时,我需要使用window.getSelection()获取所选值的开始和结束偏移量。

我的期望是,在选择第二个span文本(如'country')时,开始偏移量值将28,结束偏移量将34而不考虑其直接父级。但是,开始偏移的实际值为10,结束偏移量为16

如何才能达到预期值?

<p style="margin: 0px;">
<span>Welcome to India which</span>
<span>
<span>was great country for tourist places</span>
</span>
</p>
private onKeyUp(event: any): void {
let labelSelection = window.getSelection ? window.getSelection() : document.getSelection();
let range: any = this.labelSelection.getRangeAt(0);
}

这是一个非常棘手的问题,但玩起来很有趣。

这是一天来做的:

将鼠标事件侦听器附加到包含元素。使用event.target标识所选的开始节点和结束节点。使用这些节点可以向原始选择报告的数字添加偏移。

目录:

<p id="outer" style="margin: 0px;">
<span>Welcome to India which</span>
<span>
<span>was great country for tourist places</span>
</span>
</p>

Javascript:

const flattenNodes = node =>
Array.from(node.children).reduce((acc, curr) => {
if (curr.childElementCount > 0) {
acc.push(flattenNodes(curr))
} else {
acc.push(curr)
}
return acc
}, [])
const getOffsetForElementAtIndex = nodes => elementIndex =>
nodes.reduce((sum, node, i) => (i < elementIndex ? sum + node.textContent.length : sum), 0)
const getSelection = ev => {
const nodes = flattenNodes(ev.currentTarget).flat()
const startElementIndex = nodes.indexOf(mouseDownElement)
const endElementIndex = nodes.indexOf(ev.target)
const { startOffset, endOffset } = document.getSelection().getRangeAt(0)
const start = startOffset + getOffsetForElementAtIndex(nodes)(startElementIndex)
const end = endOffset + getOffsetForElementAtIndex(nodes)(endElementIndex)
console.log(`start: ${start}, end: ${end}`)
}
let mouseDownElement = null
const el = document.getElementById('outer')
el.addEventListener('mousedown', ev => (mouseDownElement = ev.target))
el.addEventListener('mouseup', ev => getSelection(ev))

代码笔在这里

相关内容

最新更新