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.
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;
}
});
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;
}
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.
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;
});
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>
.
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>
.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
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/
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.
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>
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>
[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.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>";
}
}
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();
}
}
});
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/
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'); //
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');
.
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();
}
});
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);
});
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.
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;
}
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.
$('<div class="temp-contenteditable-el" contenteditable="true"></div>').appendTo('body').focus().remove();
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