Prevent line/paragraph breaks in contentEditable

前端 未结 11 478
青春惊慌失措
青春惊慌失措 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 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

提交回复
热议问题