问题描述
我希望能够找出其中的DOM元素是目前在浏览器用户选择的文本present。
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()
来获得的对象重新presenting您想要的选择。
window.getSelection()
gives you a Selection object. Use selection.rangeCount
and selection.getRangeAt()
to get a Range object representing which selection you want.
现在你可以从 range.startContainer
/ startOffset
获得在选择第一个和最后一个节点和 range.endContainer
/ endOffset
。然后,您可以步行上下树拿起这两个位置之间的所有元素,例如。使用从 getElementsBetweenTree()功能href=\"http://stackoverflow.com/questions/2514125/jquery-select-elements-between-two-elements-that-are-not-siblings/2515169#2515169\">this回答。
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
猜测ING范围和比较,这是不好玩的。
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元素当前所选文本中包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!