Prevent line/paragraph breaks in contentEditable

前端 未结 11 472
青春惊慌失措
青春惊慌失措 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条回答
  • 2020-12-13 17:51

    If you are using JQuery framework, you can set it with the on method which will let you have the desired behavior on all elements even if this one is added lately.

    $(document).on('keypress', '.YourClass', function(e){
        return e.which != 13; 
    });   
    
    0 讨论(0)
  • 2020-12-13 17:57

    If you want to target all the contentEditable fields use

    $('[contenteditable]').keypress(function(e){ return e.which != 13; });
    
    0 讨论(0)
  • 2020-12-13 18:01

    You can attach an event handler to the keydown or keypress event for the contentEditable field and cancel the event if the keycode identifies itself as enter (or shift+enter).

    This will disable enter/shift+enter completely when focus is in the contentEditable field.

    If using jQuery, something like:

    $("#idContentEditable").keypress(function(e){ return e.which != 13; });
    

    ...which will return false and cancel the keypress event on enter.

    0 讨论(0)
  • 2020-12-13 18:02

    Add:

    display: flex;
    

    On the contenteditable html element

    0 讨论(0)
  • 2020-12-13 18:03

    Other than adding line breaks, the browser adds additional tags and styles (when you paste text, the browser also appends your pasted text style).

    The code below covers it all.

    • When you press enter, no line breaks will be added.
    • When you paste text, all elements added by the browser are stripped from the text.

      $('[contenteditable]').on('paste', function(e) {
          //strips elements added to the editable tag when pasting
          var $self = $(this);
          setTimeout(function() {$self.html($self.text());}, 0);
      }).on('keypress', function(e) {
           //ignores enter key
           return e.which != 13;
      });
      

    Click here for a live example

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