有没有一个函数可以使用JavaScript取消选择所有文本?

2022-08-30 04:42:51

JavaScript中是否有一个函数可以取消选择所有选定的文本?我认为它必须是一个简单的全局函数之类的。document.body.deselectAll();


答案 1

试试这个:

function clearSelection()
{
 if (window.getSelection) {window.getSelection().removeAllRanges();}
 else if (document.selection) {document.selection.empty();}
}

这将清除任何主流浏览器中常规 HTML 内容中的选择。它不会清除文本输入或 Firefox 中的选择。<textarea>


答案 2

下面是一个将清除任何选择(包括文本输入和文本区域)的版本:

演示: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;
            }
        }
    }
}