Clear a selection in Firefox

前端 未结 3 457
北荒
北荒 2020-12-03 21:16

I have this function

function smth() {
var container = null;
var newContainer = null;
if (window.getSelection) {  // all browsers, except IE before versi         


        
3条回答
  •  失恋的感觉
    2020-12-03 21:45

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

提交回复
热议问题