开发者

JavaScript: Remove current mouse highlight from the page?

开发者 https://www.devze.com 2022-12-10 13:20 出处:网络
Le开发者_开发百科t\'s say I highlight some text on the page using my mouse. How can I remove all highlighted text using JavaScript?

Le开发者_开发百科t's say I highlight some text on the page using my mouse. How can I remove all highlighted text using JavaScript?

Thank you.


I've understood the question a bit differently. I believe you want to know how to delete the selected text from the document, in which case you could use:

function deleteSelection() {
    if (window.getSelection) {
        // Mozilla
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            window.getSelection().deleteFromDocument();
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) {
        // Internet Explorer
        var ranges = document.selection.createRangeCollection();
        for (var i = 0; i < ranges.length; i++) {
            ranges[i].text = "";
        }
    }
}

If you just want to clear the highlight itself, and not remove the text being highlighted, the following should do the trick:

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


IE 4 and old Netscape used to have a method to do just this... It's not longer proper (nor supported).

Your best guess would be to use Javascript to focus() on an object, and then blur() as well -- effectively like clicking away from the object.

document.getElementById("someObject").focus();
document.getElementById("someObject").blur();
0

精彩评论

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