Deselect contenteditable element

后端 未结 3 407
臣服心动
臣服心动 2021-01-28 15:05

I am trying to remove selection inside a contenteditable field. The code I have is this:

Text

相关标签:
3条回答
  • 2021-01-28 15:45

    I found this on SO, and should be what you are looking for:

    if (window.getSelection) {
        if (window.getSelection().empty) {  // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) {  // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) {  // IE?
        document.selection.empty();
    }
    

    Working fiddle

    0 讨论(0)
  • 2021-01-28 15:51

    An answer here solved my problem, but it got deleted for some reason. It was this:

    Replacing $('h1').blur() with window.getSelection().removeAllRanges();" fixed it.

    0 讨论(0)
  • 2021-01-28 15:52

    here is the working code

    $(document).ready(function() {
      $('h1').focus();
      document.execCommand('selectAll', false, null);
    })
    
    $("#deselect").click(function(){
            window.getSelection().removeAllRanges();
      });
    

    https://jsfiddle.net/v73e3xdf/2/

    0 讨论(0)
提交回复
热议问题