1. ホーム
  2. javascript

[解決済み] Prevent contenteditable adding <div> on ENTER - Chrome

2022-04-26 22:23:55

Question

I have a contenteditable element, and whenever I type some stuff and hit ENTER it creates a new <div> and places the new line text in there. I don't like this one little bit.

Is it possible to prevent this from happening or at least just replace it with a <br> ?

Here is demo http://jsfiddle.net/jDvau/

Note: This is not an issue in firefox.

How to solved?

これを試してみてください。

$('div[contenteditable]').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 next line)
        document.execCommand('insertHTML', false, '<br/>');
        // prevent the default behaviour of return key pressed
        return false;
    }
});

デモはこちら