How can I blur a div where contentEditable=true?

前端 未结 4 880
逝去的感伤
逝去的感伤 2021-01-11 08:57

How can I blur/focusout a div where contentEditable=true? I have attempted $(elm).blur() and $(elm).attr(\'contentEditable\', false);

相关标签:
4条回答
  • 2021-01-11 09:44

    I would add another solution that is based on Omnicon's answer which is correct BTW. I have forked his fiddle and updated it.

    The trick is to remove all ranges after calling blur:

    $(".editable").blur();
    window.getSelection().removeAllRanges();
    
    0 讨论(0)
  • 2021-01-11 09:45

    $("div[contentEditable]").blur() to blur all contentEditable elements.

    $("#elementId").blur() to blur an element by its id.

    0 讨论(0)
  • 2021-01-11 09:55

    The suggested solution by Roman Resh doesn't work when you click into the element and hit enter immediately after. It won't blur but create line-breaks/divs.

    It is possible to prevent this behaviour entirely.

    See this fiddle

    $('<div class="temp-contenteditable-el" contenteditable="true"></div>') .appendTo('body').focus().remove();

    0 讨论(0)
  • 2021-01-11 10:02

    Appending to all answers, when using something like

    $(".editable").blur()
    

    think about blurring only focused, like

    $(".editable:focus").blur()
    

    If not you can get into nice probs sometimes

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