开发者

Is there a function to deselect all text using JavaScript?

开发者 https://www.devze.com 2023-03-16 19:50 出处:网络
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.Try this:

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.


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.


Here's a version that will clear any selection, including within text inputs and textareas:

Demo: 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;
            }
        }
    }
}


For Internet Explorer, you can use the empty method of the document.selection object:

document.selection.empty();

For a cross-browser solution, see this answer:

Clear a selection in Firefox


This worked incredibly easier for me ...

document.getSelection().collapseToEnd()

or

document.getSelection().removeAllRanges()

Credits: https://riptutorial.com/javascript/example/9410/deselect-everything-that-is-selected


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:

var t = document.getElementById('textarea_element');
t.focus();
t.selectionStart = 4;
t.selectionEnd = 8;

setTimeout(function()
{
 t.selectionStart = 4;
 t.selectionEnd = 4;
},1500);
0

精彩评论

暂无评论...
验证码 换一张
取 消