您可以在 JavaScript 中设置和/或更改用户的文本选择吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4183401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you set and/or change the user’s text selection in JavaScript?
提问by Paul D. Waite
In JavaScript, there are various methods for accessing the user's text selection, and creating text selections (or ranges) — see http://www.quirksmode.org/dom/range_intro.html.
在 JavaScript 中,有多种方法可以访问用户的文本选择和创建文本选择(或范围)——请参阅http://www.quirksmode.org/dom/range_intro.html。
As per that page, you can programmatically create a range, and access the text within that. But doing this doesn't change the user's text selection, or make the user have some selected text if they don't already.
根据该页面,您可以以编程方式创建一个范围,并访问其中的文本。但是这样做不会改变用户的文本选择,或者让用户选择一些文本,如果他们还没有的话。
Can you set and/or change the user's text selection in JavaScript?
您可以在 JavaScript 中设置和/或更改用户的文本选择吗?
回答by Tim Down
Yes. In all browsers you can get one or more Ranges or a TextRangefrom the user's selection, and both Rangeand TextRangehave methods for changing the contents of the range.
是的。在所有的浏览器,你可以得到一个或多个RangeS或ATextRange从用户的选择,都Range和TextRange对改变区域的内容的方法。
UPDATE
更新
You can set the user's selection by creating a Rangeand adding it to the Selectionobject in most browsers and by creating a TextRangeand calling its select()method in IE <= 8.
您可以通过在大多数浏览器中创建 a并将其Range添加到Selection对象中以及通过在 IE <= 8 中创建 aTextRange并调用其select()方法来设置用户的选择。
For example, to set the selection to encompass the contents of an element:
例如,要将选择设置为包含元素的内容:
function selectElementContents(el) {
if (window.getSelection && document.createRange) {
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
}
}
There are also several methods of the Selectionobject that can be used to change the user's selection in non-IE browsers. If you can be more specific about how you want to change the selection then it will be easier to help.
该Selection对象还有多种方法可用于在非 IE 浏览器中更改用户的选择。如果您可以更具体地了解如何更改选择,那么帮助会更容易。

