清除 Firefox 中的选择

2022-01-24 00:00:00 selection range javascript

我有这个功能

function smth() {
var container = null;
var newContainer = null;
if (window.getSelection) {  // all browsers, except IE before version 9
    alert("first if");
    var selectionRange = window.getSelection();
    if (selectionRange.rangeCount > 0) {
        var range = selectionRange.getRangeAt(0);
        container = range.commonAncestorContainer;
        newContainer = container;
    }
}
else {
    if (document.selection) {   // Internet Explorer
        alert("second if");
        var textRange = document.selection.createRange();
        container = textRange.parentElement();
    }
}

if (newContainer) {
    return newContainer.nodeName;
}
else {
    alert("Container object for the selection is not available!");
}
}     

现在,在我完成我需要对选择执行的操作后,我需要清除它.我尝试了一些没有用的东西,有什么想法吗?

Now after i do what i need to do with the selection i need to clear it. i tried a few things nothing worked, any ideas?

document.selection.clear ()    

这没用.

推荐答案

对于有问题的浏览器:

document.selection.empty()

对于其他浏览器:

window.getSelection().removeAllRanges()

参见http://help.dottoro.com/ljigixkc.php

相关文章