[英]Is there a way to select text through multiple elements?
var range = document.createRange(); var root_node = document.getElementById("test"); // Start at the `hello` element. range.setStart(root_node.childNodes[0], 2); // End in the `world` node range.setEnd(root_node.childNodes[1], 2); range.selectNodeContents(root_node); let sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
<div id="test"> <a href="#">hello</a> <span>world</span> </div>
I'd like to select text but because it's in different elements it hasn't been working.我想选择文本,但因为它在不同的元素中,所以一直没有用。 Is there a way to do this?
有没有办法做到这一点?
I don't mean to highlight both words in their entirety but portions of each word.我并不是要突出显示整个单词,而是要突出显示每个单词的一部分。
@Matt answer is in the right direction, but doesn't achieve what the OP wants, which is to "span" the range across multiple elements (nodes), while using offsets within those elements. @Matt 的回答是正确的,但没有达到 OP 的要求,即“跨越”多个元素(节点)的范围,同时在这些元素中使用偏移量。
The following achieve it:以下实现它:
var range = document.createRange(); var root_node = document.getElementById("test"); range.setStart(root_node.querySelector('a').firstChild, 2); range.setEnd(root_node.querySelector('span').firstChild, 3); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
<div id="test"> <a href="#">hello</a> <span>world</span> </div>
Note how on both setStart
and setEnd
we pass a text
node - this is the firstChild
of the anchor and span elements.请注意我们如何在
setStart
和setEnd
上传递一个text
节点 - 这是锚点和跨度元素的firstChild
节点。
For further reading on this subject, please refer to this excellent explanation .有关此主题的进一步阅读,请参阅此出色的解释。
You called setStart
twice, instead of setStart
followed by setEnd
, and you are specifying an offset of 2 in each case, but I don't think you want an offset because that puts your node index out of range (and throws an error).您调用了
setStart
两次,而不是setStart
后跟setEnd
,并且您在每种情况下都指定了 2 的偏移量,但我认为您不需要偏移量,因为这会使您的节点索引超出范围(并引发错误)。
var range = document.createRange(); var root_node = document.getElementById("test"); // Start at the `hello` element. range.setStart(root_node.childNodes[0], 0); // End in the `world` node range.setEnd(root_node.childNodes[1], 0); range.selectNodeContents(root_node); let sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
<div id="test"> <a href="#">hello</a> <span>world</span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.