[英]Get multiple elements from document.getSelection()
How can I get the multiple elements a user has selected from document.getSelection()
? 如何获取用户从
document.getSelection()
选择的多个元素?
document.getElementById("hello").onclick = function() {
selection = document.getSelection();
if(selection) {
console.log(selection.anchorNode.textContent);
}
};
http://jsbin.com/qisawudofa/edit?html,js,console,output http://jsbin.com/qisawudofa/edit?html,js,console,output
It seems to only return the element that was selected first, but in my case I need to get all of them. 它似乎只返回首先选择的元素,但在我的情况下,我需要获得所有这些元素。
Alternatively, is there a way to at least know when multiple elements have been selected? 或者,有没有办法至少知道何时选择了多个元素?
You're probably most interested in the Ranges
that make up the selection. 您可能最感兴趣的是组成选择的
Ranges
。 Remember the user can make multiple selections all over the page. 请记住,用户可以在整个页面上进行多项选择。 Each continuous area of selection will get its own instance of
Range
. 每个连续的选择区域都将获得自己的
Range
实例。
You'll need to iterate over all of the ranges. 您需要迭代所有范围。 For each of them you can see where it starts and where it ends:
对于每个人,您可以看到它的起始位置和结束位置:
if (selection) {
for (i=0; i<selection.rangeCount; i++) {
range = selection.getRangeAt(i);
if (range) {
console.log(range.startContainer);
console.log(range.endContainer);
}
}
}
But for the example described in your code you'll need to consider two more things: 但是对于代码中描述的示例,您还需要考虑两件事:
Only if the user very accurately selects a paragraph will you get the paragraph's node in startContainer
. 只有当用户非常准确地选择段落时,才会在
startContainer
获得段落的节点。 They might start their start selection even one character after the beginning of the paragraph and then you'll get a text node with the paragraph as its parent. 他们可能会在段落开头后开始选择一个字符,然后你会得到一个文本节点,段落作为其父节点。
The Range
only gives you the start and the end of the selection for that range. Range
仅为您提供该Range
选择的开始和结束。 It doesn't directly give you all of the elements in between. 它并不直接为您提供介于两者之间的所有元素。 So if the user selects more than 2 paragraphs, you'll need to figure out exactly which paragraphs are between start and end yourself.
因此,如果用户选择了超过2个段落,您需要自己确定哪些段落在开始和结束之间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.