是否有使用 JavaScript 取消选择所有文本的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6562727/
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
Is there a function to deselect all text using JavaScript?
提问by NoodleOfDeath
Is there a function in javascript to just deselect all selected text? I figure it's got to be a simple global function like document.body.deselectAll();
or something.
javascript中是否有一个功能可以取消选择所有选定的文本?我认为它必须是一个简单的全局函数之类的document.body.deselectAll();
。
回答by Ankur
Try this:
尝试这个:
function clearSelection()
{
if (window.getSelection) {window.getSelection().removeAllRanges();}
else if (document.selection) {document.selection.empty();}
}
This will clear a selection in regular HTML content in any major browser. It won't clear a selection in a text input or <textarea>
in Firefox.
这将清除任何主要浏览器中常规 HTML 内容中的选择。它不会清除文本输入或<textarea>
Firefox 中的选择。
回答by Tim Down
Here's a version that will clear any selection, including within text inputs and textareas:
这是一个可以清除任何选择的版本,包括文本输入和文本区域:
Demo: http://jsfiddle.net/SLQpM/23/
演示:http: //jsfiddle.net/SLQpM/23/
function clearSelection() {
var sel;
if ( (sel = document.selection) && sel.empty ) {
sel.empty();
} else {
if (window.getSelection) {
window.getSelection().removeAllRanges();
}
var activeEl = document.activeElement;
if (activeEl) {
var tagName = activeEl.nodeName.toLowerCase();
if ( tagName == "textarea" ||
(tagName == "input" && activeEl.type == "text") ) {
// Collapse the selection to the end
activeEl.selectionStart = activeEl.selectionEnd;
}
}
}
}
回答by Luke Girvin
For Internet Explorer, you can use the empty methodof the document.selection object:
对于 Internet Explorer,您可以使用document.selection 对象的空方法:
document.selection.empty();
文档.selection.empty();
For a cross-browser solution, see this answer:
有关跨浏览器的解决方案,请参阅此答案:
回答by John
For a textarea
element with at least 10 characters the following will make a small selection and then after a second and a half deselect it:
对于textarea
至少有 10 个字符的元素,以下将进行一个小的选择,然后在一秒半后取消选择它:
var t = document.getElementById('textarea_element');
t.focus();
t.selectionStart = 4;
t.selectionEnd = 8;
setTimeout(function()
{
t.selectionStart = 4;
t.selectionEnd = 4;
},1500);