Prevent contenteditable adding
on ENTER - Ch

2019-01-04 07:33发布

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.

20条回答
戒情不戒烟
2楼-- · 2019-01-04 08:06

This is browser directed HTML5 editor. You can wrap your text with <p>...</p>, then whenever you press ENTER you get <p></p>. Also, the editor works this way that whenever you press SHIFT+ENTER it inserts <br />.

<div contenteditable="true"><p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor veniam asperiores laudantium repudiandae doloremque sed perferendis obcaecati delectus autem perspiciatis aut excepturi et nesciunt error ad incidunt impedit quia dolores rerum animi provident dolore corporis libero sunt enim. Ad magnam omnis quidem qui voluptas ut minima similique obcaecati doloremque atque!
<br /><br />
Type some stuff, hit ENTER a few times, then press the button.
</p>
</div>

Check this: http://jsfiddle.net/ZQztJ/

查看更多
欢心
3楼-- · 2019-01-04 08:10

Try this

$('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><br>');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });

Demo Here

查看更多
对你真心纯属浪费
4楼-- · 2019-01-04 08:10

First we need to capture every key user enter to see if enter is pressed then we prevent the <div> creation and we create our own <br> tag.

There's one problem, when we create it our cursor stay at the same position so we use Selection API to place our cursor at the end.

Don't forget to add a <br> tag at the end of your text because if you don't the first enter won't do a new line.

$('div[contenteditable]').on('keydown', function(e) {
    var key = e.keyCode,
        el  = $(this)[0];
    // If Enter    
    if (key === 13) {
        e.preventDefault(); // Prevent the <div /> creation.
        $(this).append('<br>'); // Add the <br at the end

        // Place selection at the end 
        // http://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser
        if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
        }
    }
});

Fiddle

查看更多
戒情不戒烟
5楼-- · 2019-01-04 08:10

Prevent New Div creation in content editable Div on each enter key: Solution That I have find is very simple:

var newdiv = document.createElement("div"); 
newdiv.innerHTML = "Your content of div goes here";
myEditablediv.appendChild(newdiv);

This --- innerHTML content prevent New Div creation in content editable Div on each enter key.

查看更多
相关推荐>>
6楼-- · 2019-01-04 08:11
document.execCommand('defaultParagraphSeparator', false, 'p');

It overrides the default behavior to have paragraph instead.

On chrome the default behavior on enter is:

<div>
    <br>
</div>

With that command it is gonna be

<p>
    <br>
</p>

Now that it's more linear across it's easy to have only <br> would you need to.

查看更多
贪生不怕死
7楼-- · 2019-01-04 08:13
if (navigator.userAgent.toLowerCase().indexOf('msie') > -1) {
   var range = document.getSelection();
   range.pasteHTML(range.htmlText + '<br><br>');
}
else if(navigator.userAgent.toLocaleLowerCase().indexOf('trident') > -1)                           {
   var range = document.getSelection().getRangeAt(0); //get caret
   var nnode = document.createElement('br');
   var bnode = document.createTextNode('\u00A0'); //&nbsp;
   range.insertNode(nnode);
   this.appendChild(bnode);
   range.insertNode(nnode);                                
}
else
   document.execCommand('insertHTML', false, '<br><br>')

Where this is the actual context which means document.getElementById('test');.

查看更多
登录 后发表回答