[英]How can I prevent Range.selectNode() selecting too much of the DOM when attempting to select a node injected with appendChild()?
I'm facing an issue with the combination of using appendChild()
and Range.selectNode()
in JavaScript. 我在JavaScript中使用
appendChild()
和Range.selectNode()
的组合遇到了问题。
When attempting to use a range to select the newly-appended <textarea>
node, it selects too much of the DOM. 当尝试使用范围来选择新附加的
<textarea>
节点时,它会选择太多的DOM。 Copying and pasting the selection seems to just contain a space. 复制和粘贴选择似乎只包含一个空格。
However, if I put the <textarea>
node into the DOM from the start (ie don't add it with appendChild()
) then it works perfectly well and I can copy and paste the selected text as expected. 但是,如果我从一开始就将
<textarea>
节点放入DOM中(即不要用appendChild()
添加它),那么它的效果非常好,我可以按预期复制和粘贴所选文本。
Note that the CSS isn't really necessary here, but it highlights the fact that the selection contains more than just the <textarea>
(or at least it does in Chrome). 请注意,CSS在这里并不是必需的,但它突出了这样一个事实,即选择包含的不仅仅是
<textarea>
(或者至少它包含在Chrome中)。
HTML: HTML:
<div>
<a class="hoverTrigger">Click to trigger textarea element with selected text</a>
</div>
CSS: CSS:
.floating {
position: absolute;
}
JavaScript/jQuery (run on DOM ready): JavaScript / jQuery(在DOM上运行):
$(".hoverTrigger").click(createAndSelectStuff);
function createAndSelectStuff() {
var textArea = document.createElement("textarea");
textArea.className = "floating";
textArea.value = "Some dynamic text to select";
this.parentNode.appendChild(textArea);
selectObjectText(textArea);
return false;
}
function selectObjectText(container) {
var range = document.createRange();
range.selectNode(container);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
Here's a jsFiddle . 这是一个jsFiddle 。
This is what the resulting selection looks like in Chrome: 这是Chrome中的结果选择:
How can I stop this happening, and just select the desired text? 如何阻止这种情况发生,只需选择所需的文字?
Replace your call to selectObjectText
with: 将您的调用替换为
selectObjectText
:
container.setSelectionRange(0, container.value.length);
The problem with textarea
elements is that they do not hold their contents in DOM nodes. textarea
元素的问题在于它们不在DOM节点中保存它们的内容。 The text value is a property of the element. 文本值是元素的属性。 When you call
range.selectNode
, what happens is that the range is set so as to encompass the node you pass to the function and the children node of this node, but since a textarea
does not store its text in children nodes, then you select only the textarea
. 当你调用
range.selectNode
,会发生的是设置范围以包含传递给函数的节点和该节点的子节点,但由于textarea
不将其文本存储在子节点中,因此您选择只有textarea
。
setSelectionRange
works with the value of an input element so it does not suffer from this problem. setSelectionRange
使用输入元素的值,因此它不会遇到此问题。 You might want to check the compatibility matrix here to check which browsers support it. 您可能需要在此处检查兼容性矩阵以检查哪些浏览器支持它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.