Clear a selection in Firefox

霸气de小男生 提交于 2019-11-26 18:31:36

问题


I have this function

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 ()    

this didnt work.


回答1:


For the problematic browser:

document.selection.empty()

For other browsers:

window.getSelection().removeAllRanges()

See http://help.dottoro.com/ljigixkc.php




回答2:


Note: in case you are selecting the text of an input or textarea element then your code would have more cross browser support if you would use the standard native html element select method of the input or textarea.

If an html input or textarea element was selected using the native select method then using the methods suggested above does not work on my firefox 44.0.2. What worked for it, and I suppose works on ALL BROWSERS, is running the following code which creates a new element and selects it. The new element can't be with display:none or visibility:hidden because then it is not selected in my Firebox so the trick is to make it invisible by forcing all size attributes to 0\none.

var tempElement = document.createElement("input");
tempElement.style.cssText = "width:0!important;padding:0!important;border:0!important;margin:0!important;outline:none!important;boxShadow:none!important;";
document.body.appendChild(tempElement);
tempElement.select();
/* Use removeChild instead of remove because remove is less supported */
document.body.removeChild(tempElement);



回答3:


Use tinymce.activeEditor.selection.collapse() if that does not work then use const range = tinymce.activeEditor.dom.createRng(); tinymce.activeEditor.selection.setRng(range)



来源:https://stackoverflow.com/questions/6186844/clear-a-selection-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!