Noo*_*ath 84 javascript selection
javascript中是否有一个函数可以取消选择所有选定的文本?我认为它必须是一个简单的全局函数document.body.deselectAll();
或类似的东西.
Ank*_*kur 141
试试这个:
function clearSelection()
{
if (window.getSelection) {window.getSelection().removeAllRanges();}
else if (document.selection) {document.selection.empty();}
}
Run Code Online (Sandbox Code Playgroud)
这将清除任何主要浏览器中常规HTML内容的选择.它不会清除文本输入或<textarea>
Firefox中的选择.
Tim*_*own 26
这是一个清除任何选择的版本,包括文本输入和textareas:
演示: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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这对我来说非常容易......
document.getSelection().collapseToEnd()
Run Code Online (Sandbox Code Playgroud)
或者
document.getSelection().removeAllRanges()
Run Code Online (Sandbox Code Playgroud)
学分:https://riptutorial.com/javascript/example/9410/deselect-everything-that-is-selected
对于Internet Explorer,您可以使用document.selection对象的空方法:
document.selection.empty();
对于跨浏览器解决方案,请参阅以下答案: