问题描述
我想能够在浏览器中找出用户当前选择的文本中存在哪些DOM元素。
I want to be able to find out which DOM elements are present in the text currently selected by the user in the browser.
document.getSelection()将会显示当前选定的文本。但是我们如何确定这个文本选择中包含哪些DOM元素?
document.getSelection() would get us the currently selected text. But how can we determine which DOM elements are contained in this text selection?
推荐答案
window.getSelection )
为您提供目的。使用 selection.rangeCount
和 selection.getRangeAt()
获取。
Now you can get the first and last nodes in the selection from range.startContainer
/startOffset
and range.endContainer
/endOffset
. You could then walk up and down the tree to pick up all the elements in between those two positions, eg. using the getElementsBetweenTree()
function from this answer.
不幸的是,IE的模型与W3和HTML5标准截然不同,一般情况更糟。它不会放弃开始和结束位置几乎一样容易,而不是以任何可靠的方式。所有你得到的是 parentElement
来告诉你共同的祖先,从那里你只能猜测范围是基于创建一个新的范围,并调用 moveToElementText
,然后使用选择范围 compareEndPoints
。如果您需要知道确切的文本选择,您可以根据 moveStart
/ moveEnd
比较,这根本不是很有趣。
Unfortunately, IE's TextRange model is totally different to the W3 and HTML5 standard, and in general much worse. It does't give up the start and end positions nearly as easily, and not in any reliable way. All you get is parentElement
to tell you the common ancestor, and from there you're limited to guessing where the range is based on creating a new Range and calling moveToElementText
on it then compareEndPoints
with the selection range. And if you need to know the exact text selection you're then guessing based on moveStart
/moveEnd
ing the range and comparing, which isn't fun at all.
这篇关于确定当前文本选择包含哪些DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!