Contenteditable paragraph tag on enter

2019-02-04 22:26发布

I was wondering if there is an acceptable way to force all major browsers to insert paragraph tag instead of the default tag that they insert on pressing enter key when contentEditable is true.

As far as I know IE inserts p automatically. But Google Chrome inserts div tag and Firefox inserts br (WTF?!).

Thanks in advance!

3条回答
冷血范
2楼-- · 2019-02-04 22:30

you can use document.execCommand('formatBlock', false, 'p'); in event like keypress or keydown, etc. to use paragraphs after enter press. For example:

element.addEventListener('keypress', function(ev){
    if(ev.keyCode == '13')
        document.execCommand('formatBlock', false, 'p');
}, false);
查看更多
时光不老,我们不散
3楼-- · 2019-02-04 22:40

As its build in the browser you can't change that behaviour. You could work around by detecting browser and replacing elements correspondingly. Very ugly, I know.

Also check WhatWG for background: http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2011-May/031577.html

查看更多
三岁会撩人
4楼-- · 2019-02-04 22:52

I had this same problem and found the solution (CHROME, MSIE, FIREFOX), follow my code in the link.

$(document).on('click','#myButton',function() {
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
        var str = $('#myDiv').html().replace(/<br>/gi,'').replace(/<div>/gi,'<br>').replace(/<\/div>/gi,'');
    else if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1)
        var str = $('#myDiv').html().replace(/<\/br>/gi,'').replace(/<br>/gi,'<br>').replace(/<\/br>/gi,'');
    else if (navigator.userAgent.toLowerCase().indexOf("msie") == -1)
        var str = $('#myDiv').html().replace(/<br>/gi,'').replace(/<p>/gi,'<br>').replace(/<\/p>/gi,'');    
    $('#myDiv2').removeClass('invisible').addClass('visible').text(str);
    $('#myDiv3').removeClass('invisible').addClass('visible').html(str);
});

https://jsfiddle.net/kzkxo70L/1/

查看更多
登录 后发表回答