Prevent Firefox from making a new contenteditable

2019-07-29 17:50发布

问题:

I have a contenteditable div on my site which works great.

On Chrome i can just use the return key to add another line.

On Firefox it creates a new (extra) div.

I know I can use shift+return, but I don't think the users will now that :)

Is it possible to prevent this behaviour?

Check out the fiddle: http://jsfiddle.net/D7MJx/

I've tried it with FF 3.6

EDIT: The same thing happens on IE8

回答1:

Ok I kinda figured it out now.

It's not the best (read cleanest) solution, but it works for me.

Only have tested this on Chrome, but I think other browsers will work the same.

I ended up doing this:

  $('div[contenteditable=true]').keydown(function(e) {
    // trap the return key being pressed
    if (e.keyCode == 13) {
      // insert 2 br tags (if only one br tag is inserted the cursor won't go to the second line)
      document.execCommand('insertHTML', false, '<br><br>');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });


回答2:

I think you want the insertBrOnReturn command.

document.getElementById('myRichEditArea').contentDocument.execCommand('insertBrOnReturn',false, true)

https://developer.mozilla.org/en/rich-text_editing_in_mozilla

The Mozilla docs say insertBrOnReturn is not supported by IE but the docs are old and probably means IE7 or below. There's probably another way to do it in IE.