Zapobieganie dodawaniu treści na ENTER-Chrome

Mam element contenteditable i za każdym razem, gdy wpiszę jakieś rzeczy i nacisnę ENTER, tworzy on nowy <div> i umieszcza tam nowy tekst wiersza. Nie podoba mi się to.

Czy można temu zapobiec lub przynajmniej zastąpić go <br>?

Oto demo http://jsfiddle.net/jDvau/

Uwaga: to nie jest problem w Firefoksie.

Author: iConnor, 2013-09-01

20 answers

Spróbuj tego

$('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 Tutaj

 137
Author: Ram G Athreya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-02 14:50:52

Możesz to zrobić tylko za pomocą zmiany CSS:

div{
    background: skyblue;
    padding:10px;
    display: inline-block;
}

pre{
    white-space: pre-wrap;
    background: #EEE;
}

Http://jsfiddle.net/ayiem999/HW43Q/

 40
Author: airi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-12 17:50:51

Dodaj styl display:inline-block; do contenteditable, nie wygeneruje div, p i span automatycznie w Chrome.

 26
Author: Le Tung Anh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-11 03:22:19

Spróbuj tego:

$('div[contenteditable="true"]').keypress(function(event) {

    if (event.which != 13)
        return true;

    var docFragment = document.createDocumentFragment();

    //add a new line
    var newEle = document.createTextNode('\n');
    docFragment.appendChild(newEle);

    //add the br, or p, or something else
    newEle = document.createElement('br');
    docFragment.appendChild(newEle);

    //make the br replace selection
    var range = window.getSelection().getRangeAt(0);
    range.deleteContents();
    range.insertNode(docFragment);

    //create a new range
    range = document.createRange();
    range.setStartAfter(newEle);
    range.collapse(true);

    //make the cursor there
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);

    return false;
});

Http://jsfiddle.net/rooseve/jDvau/3/

 19
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-05 10:57:08

Użyj shift+Wprowadź zamiast Wprowadź , aby umieścić pojedynczy znacznik <br> lub zawinąć tekst w znaczniki <p>.

 10
Author: Blake Plumb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-06 20:03:22
document.execCommand('defaultParagraphSeparator', false, 'p');

Nadpisuje domyślne zachowanie zamiast akapitu.

W chrome domyślne zachowanie enter to:

<div>
    <br>
</div>

Z tą komendą będzie

<p>
    <br>
</p>
Teraz, gdy jest bardziej liniowy, łatwo jest mieć tylko <br>.
 8
Author: Ced,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-29 16:18:19

Sposób, w jaki contenteditable zachowuje się po naciśnięciu enter zależy od przeglądarek, <div> dzieje się w webkit (chrome, safari) i IE.

Zmagałem się z tym kilka miesięcy temu i poprawiłem to w ten sposób:

//I recommand you trigger this in case of focus on your contenteditable
if( navigator.userAgent.indexOf("msie") > 0 || navigator.userAgent.indexOf("webkit") > 0 ) {
    //Add <br> to the end of the field for chrome and safari to allow further insertion
    if(navigator.userAgent.indexOf("webkit") > 0)
    {
        if ( !this.lastChild || this.lastChild.nodeName.toLowerCase() != "br" ) {
            $(this).html( $(this).html()+'<br />' );
        }
    }

    $(this).keypress( function(e) {
        if( ( e.keyCode || e.witch ) == 13 ) {
            e.preventDefault();

            if( navigator.userAgent.indexOf("msie") > 0 ) {
                insertHtml('<br />');
            }
            else {
              var selection = window.getSelection(),
              range = selection.getRangeAt(0),
              br = document.createElement('br');

              range.deleteContents();
              range.insertNode(br);
              range.setStartAfter(br);
              range.setEndAfter(br);
              range.collapse(false);

              selection.removeAllRanges();
              selection.addRange(range);
            }
        }
    });
}

Mam nadzieję, że to pomoże, i przepraszam za mój angielski, jeśli nie jest tak jasny, jak trzeba.

EDIT : korekta usuniętej funkcji jQuery jQuery.browser

 6
Author: Elie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-08 15:39:56

Użyłbym stylizacji (Css), aby rozwiązać problem.

div[contenteditable=true] > div {
  padding: 0;
} 
Firefox rzeczywiście dodaje blok elementu break
, podczas gdy Chrome zawija każdą sekcję w znacznik. Css daje divs padding 10px wraz z kolorem tła.
div{
  background: skyblue;
  padding:10px;
}

Alternatywnie możesz odtworzyć ten sam pożądany efekt w jQuery:

var style = $('<style>p[contenteditable=true] > div { padding: 0;}</style>');
$('html > head').append(style);

Oto widelec Twoich skrzypiec http://jsfiddle.net/R4Jdz/7/

 4
Author: cbayram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-11 16:17:06

Spróbuj użyć ckeditor. Zapewnia również formatowanie jak ten w SOF.

Https://github.com/galetahub/ckeditor

 3
Author: Dan Rey Oquindo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-05 11:12:59

Możesz zawinąć akapity tagiem <p>, Na przykład pojawi się on w nowej linii zamiast div Przykład:
<div contenteditable="true"><p>Line</p></div>
Po wstawieniu nowego ciągu:
<div contenteditable="true"><p>Line</p><p>New Line</p></div>

 3
Author: nes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 08:20:12

Możesz mieć oddzielne znaczniki <p> dla każdej linii, a nie używać znaczników <br> i uzyskać większą zgodność z przeglądarką po wyjęciu z pudełka.

Aby to zrobić, umieść znacznik <p> z domyślnym tekstem wewnątrz contenteditable div.

Na przykład zamiast:

<div contenteditable></div>

Użycie:

<div contenteditable>
   <p>Replace this text with something awesome!</p>
</div>

Jsfiddle

[5]}przetestowano w Chrome, Firefox i Edge, a drugi działa tak samo w każdym.

Pierwszy jednak tworzy divy w Chrome, tworzy podziały linii w Firefox, a w Edge tworzy divs i kursor jest umieszczany z powrotem na początku bieżącego div zamiast przesuwać się do następnego.

Testowane w Chrome, Firefox i Edge.
 3
Author: Josh Powlison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-17 03:42:06

Dodaj prevent default do div

document.body.div.onkeydown = function(e) {
    if ( e.keycode == 13 ){
        e.preventDefault();
            //add a <br>
        div = document.getElementById("myDiv");
        div.innerHTML += "<br>";
    }
}
 2
Author: Math chiller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-05 11:09:37

Najpierw musimy przechwycić każdy klawisz enter, aby zobaczyć, czy enter jest wciśnięty, następnie zapobiegamy tworzeniu <div> i tworzymy własny znacznik <br>.

Jest jeden problem, gdy go tworzymy, nasz kursor pozostaje w tej samej pozycji, więc używamy Selection API, aby umieścić nasz kursor na końcu.

Nie zapomnij dodać znacznika <br> na końcu tekstu, ponieważ jeśli nie pierwszy wpis nie zrobi nowej linii.

$('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

 2
Author: L105,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 01:25:39

To jest edytor HTML5 skierowany do przeglądarki. Możesz zawinąć swój tekst za pomocą <p>...</p>, a następnie za każdym razem, gdy naciśniesz ENTER, otrzymasz <p></p>. Ponadto edytor działa w ten sposób, że po naciśnięciu SHIFT + ENTER wstawia <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>

Sprawdź to: http://jsfiddle.net/ZQztJ/

 2
Author: Mehdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 03:52:14
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>')

Gdzie this jest rzeczywistym kontekstem, który oznacza document.getElementById('test');.

 2
Author: webprogrammer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 17:15:45

Another way to do it

$('button').click(function(){
    $('pre').text($('div')[0].outerHTML)
});

$("#content-edit").keydown(function(e) {
    if(e.which == 13) {
       $(this).find("div").prepend('<br />').contents().unwrap();
      }
});

Http://jsfiddle.net/jDvau/11/

 1
Author: BlueUnicorn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 06:11:01

Miałem ten sam problem i znalazłem rozwiązanie (CHROME, MSIE, FIREFOX), wykonaj mój kod w linku.

$(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/

 1
Author: Fábio Zangirolami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-28 03:56:24

Zapobiec tworzeniu nowego Div w treści edytowalny Div na każdym klawiszu enter: rozwiązanie, które mam znaleźć jest bardzo proste:

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

Ta - - - zawartość innerHTML zapobiega tworzeniu nowego Div w edytowalnym Div zawartości dla każdego klawisza enter.

 0
Author: DrShyam Babu Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-19 10:01:19

Rozwiązanie polecenia inserHTML robi dziwne rzeczy, gdy zagnieżdżasz elementy contenteditable.

Wzięłam kilka pomysłów z wielu odpowiedzi tutaj, i to wydaje się odpowiadać moim potrzebom NA teraz:

element.addEventListener('keydown', function onKeyDown(e) {

    // Only listen for plain returns, without any modifier keys
    if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
        return;
    }

    let doc_fragment = document.createDocumentFragment();

    // Create a new break element
    let new_ele = document.createElement('br');
    doc_fragment.appendChild(new_ele);

    // Get the current selection, and make sure the content is removed (if any)
    let range = window.getSelection().getRangeAt(0);
    range.deleteContents();

    // See if the selection container has any next siblings
    // If not: add another break, otherwise the cursor won't move
    if (!hasNextSibling(range.endContainer)) {
        let extra_break = document.createElement('br');
        doc_fragment.appendChild(extra_break);
    }

    range.insertNode(doc_fragment);

    //create a new range
    range = document.createRange();
    range.setStartAfter(new_ele);
    range.collapse(true);

    //make the cursor there
    let sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);

    e.stopPropagation();
    e.preventDefault();

    return false;
});

// See if the given node has a next sibling.
// Either any element or a non-empty node
function hasNextSibling(node) {

    if (node.nextElementSibling) {
        return true;
    }

    while (node.nextSibling) {
        node = node.nextSibling;

        if (node.length > 0) {
            return true;
        }
    }

    return false;
}
 0
Author: skerit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-31 12:07:30

Można całkowicie zapobiec temu zachowaniu.

Zobacz to skrzypce

$('<div class="temp-contenteditable-el" contenteditable="true"></div>').appendTo('body').focus().remove();
 -1
Author: Omnicon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-29 19:37:40