JavaScript 设置窗口选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6190143/
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
JavaScript Set Window selection
提问by Richard J. Ross III
In JavaScript, there is a method window.getSelection()
, that lets me get the current selection that the user has made.
在 JavaScript 中,有一种方法window.getSelection()
可以让我获取用户所做的当前选择。
Is there a corresponding function, something like window.setSelection()
, that will let me set, or clear, the current selection?
是否有相应的功能,例如window.setSelection()
,可以让我设置或清除当前选择?
采纳答案by stefgosselin
Maybe this will do it:
也许这会做到:
window.selection.clear();
Crossbrowser version:
跨浏览器版本:
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
回答by Tim Down
Clearing the selection in all major browsers:
清除所有主要浏览器中的选择:
function clearSelection() {
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else if (document.selection) {
document.selection.empty();
}
}
Selecting content requires use of DOM Range
and Selection
objects in most browsers and TextRange
objects in IE < 9. Here's a simple cross-browser example that selects the contents of a particular element:
选择内容需要使用大多数浏览器中的DOMRange
和Selection
对象,以及TextRange
IE < 9 中的对象。 下面是一个简单的跨浏览器示例,用于选择特定元素的内容:
function selectElement(element) {
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(element);
sel.addRange(range);
} else if (document.selection) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(element);
textRange.select();
}
}
回答by Pointy
In browsers that support the "selection" and "range" stuff, you'll want to create a range object and then set its start/end. The Mozilla documentationfor the "range" object has a lot of information.
在支持“选择”和“范围”内容的浏览器中,您需要创建一个范围对象,然后设置它的开始/结束。“范围”对象的Mozilla 文档有很多信息。
Chrome doesn't support this, at least not with that API, and I bet Safari doesn't either.
Chrome 不支持这个,至少不支持那个 API,我敢打赌 Safari 也不支持。
edit— thanks to @Tim Down for noting that WebKit (Chrome & Safari) do indeed support this, which means my jsfiddle had a typo or something!
编辑——感谢@Tim Down 注意到 WebKit(Chrome 和 Safari)确实支持这一点,这意味着我的 jsfiddle 有一个错字或什么的!