Prevent line/paragraph breaks in contentEditable

前端 未结 11 471
青春惊慌失措
青春惊慌失措 2020-12-13 17:18

When using contentEditable in Firefox, is there a way to prevent the user from inserting paragraph or line breaks by pressing enter or shift+enter?

相关标签:
11条回答
  • I came here searching for the same answer, and was surprised to find it's a rather simple solution, using the tried and true Event.preventDefault()

    const input = document.getElementById('input');
    
    input.addEventListener('keypress', (e) => {
      if (e.which === 13) e.preventDefault();
    });
    <div contenteditable="true" id="input">
      You can edit me, just click on me and start typing.
      However, you can't add any line breaks by pressing enter.
    </div>

    0 讨论(0)
  • 2020-12-13 17:43

    Add the following CSS rule to hide line breaks. This is only a style setting, you should add some event handlers to prevent inserting line breaks:

    .your_editable br {
        display: none
    }
    
    0 讨论(0)
  • 2020-12-13 17:43
    $("#idContentEditable").keypress(function(e){ return e.which != 13; });
    

    Solution proposed by Kamens doesn't work in Opera, you should attach event to document instead.

    /**
     * Pass false to enable
     */
    var disableEnterKey = function(){
        var disabled = false;
    
        // Keypress event doesn't get fired when assigned to element in Opera
        $(document).keypress(function(e){
            if (disabled) return e.which != 13;
        });                 
    
        return function(flag){
            disabled = (flag !== undefined) ? flag : true;
        }
    }();    
    
    0 讨论(0)
  • 2020-12-13 17:43

    Use CSS:

    word-break: break-all;
    

    For me, its worked!

    0 讨论(0)
  • 2020-12-13 17:48

    This is possible with Vanilla JS, with the same effort:

    document.getElementById('idContentEditable').addEventListener('keypress', (evt) => {
        if (evt.which === 13) {
            evt.preventDefault();
        }
    });
    

    You should not use jQuery for the most simple things. Also, you may want to use "key" instead of "which": https://developer.mozilla.org/en-US/docs/Web/Events/keypress

    Update, since keypress is deprecated:

    document.getElementById('idContentEditable').addEventListener('keydown', (evt) => {
        if (evt.keyCode === 13) {
            evt.preventDefault();
        }
    });
    
    0 讨论(0)
  • another option is to allow breaks to be entered but remove them on blur. this has the advantage of dealing with pasted content. your users will either love it or hate it (depending on your users).

    function handle_blur(evt){
      var elt=evt.target; elt.innerText=elt.innerText.replace(/\n/g,' ');
    }
    

    then, in html:

    <span onblur="handle_blur(event)" contenteditable>editable text</span>
    
    0 讨论(0)
提交回复
热议问题