Clicking outside a contenteditable div stills give focus to it?

后端 未结 5 1222
独厮守ぢ
独厮守ぢ 2020-12-14 15:52

For some reason I need to use contenteditable div instead of normal text input for inputting text. (for some javascript library) It works fine until I found that when I set

5条回答
  •  有刺的猬
    2020-12-14 16:14

    How about a little jQuery?

    $(".outside").click(function(e){
        $(e.target).siblings(".text-input").blur();
        window.getSelection().removeAllRanges();
    });
    

    And if IRL you need to account for clicks on contenteditable=true siblings' children:

    $(".outside").click(function(e){
        if ($(e.target).siblings(".text-input").length != 0){
            $(e.target).siblings(".text-input").blur();
            window.getSelection().removeAllRanges();
        } 
        else {
            $(e.target).parentsUntil(".outside").last().siblings(".text-input").blur();
            window.getSelection().removeAllRanges();
        }
    });
    

    window.getSelection().removeAllRanges();"The trick is to remove all ranges after calling blur"

提交回复
热议问题