내용 편집 가능한 추가 방지 ENTER에서-Chrome
나는 contenteditable
요소를 가지고 있으며 , 물건을 입력하고 칠 때마다 ENTER
새로운 것을 만들고 <div>
거기에 새로운 줄 텍스트를 넣 습니다. 나는 이것을 조금 좋아하지 않습니다.
이 문제가 발생하는 것을 막을 수 <br>
있습니까? 아니면 적어도 ?
데모는 http://jsfiddle.net/jDvau/입니다.
참고 : 이것은 firefox의 문제가 아닙니다.
이 시도
$('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;
}
});
CSS 변경만으로이 작업을 수행 할 수 있습니다.
div{
background: skyblue;
padding:10px;
display: inline-block;
}
pre{
white-space: pre-wrap;
background: #EEE;
}
http://jsfiddle.net/ayiem999/HW43Q/
스타일을 추가 display:inline-block;
하기 위해 contenteditable
, 그것은 생성하지 않습니다 div
, p
그리고 span
자동으로 크롬있다.
이 시도:
$('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/
document.execCommand('defaultParagraphSeparator', false, 'p');
대신 단락을 갖도록 기본 동작을 재정의합니다.
크롬에서 입력시 기본 동작은 다음과 같습니다.
<div>
<br>
</div>
그 명령으로
<p>
<br>
</p>
이제 더 선형 적이므로 <br>
필요한 것만 있으면됩니다.
단일 태그를 넣거나 텍스트를 태그로 묶는 대신 shift+ enter를 사용하십시오 .enter<br>
<p>
contenteditable
누를 때 작동 하는 방식은 enter브라우저, <div>
웹킷 (크롬, 사파리) 및 IE에서 발생합니다.
몇 달 전에이 문제로 어려움을 겪고 다음과 같이 수정했습니다.
//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);
}
}
});
}
도움이 되길 바랍니다. 필요한만큼 명확하지 않으면 영어로 죄송합니다.
편집 : 제거 된 jQuery 함수 수정jQuery.browser
div에 기본값 방지를 추가하십시오.
document.body.div.onkeydown = function(e) {
if ( e.keycode == 13 ){
e.preventDefault();
//add a <br>
div = document.getElementById("myDiv");
div.innerHTML += "<br>";
}
}
스타일링 (Css)을 사용하여 문제를 해결합니다.
div[contenteditable=true] > div {
padding: 0;
}
Firefox는 실제로 block element break를 추가하는
반면 Chrome은 각 섹션을 태그로 묶습니다. CSS는 div에 배경색과 함께 10px 의 패딩을 제공합니다 .
div{
background: skyblue;
padding:10px;
}
또는 jQuery에서 동일한 원하는 효과를 복제 할 수 있습니다.
var style = $('<style>p[contenteditable=true] > div { padding: 0;}</style>');
$('html > head').append(style);
여기에 바이올린 포크가 있습니다. http://jsfiddle.net/R4Jdz/7/
<p>
태그를 사용하는 대신 각 줄에 대해 별도의 태그를 사용할 수 있으며 <br>
기본적으로 브라우저 호환성이 향상됩니다.
이렇게하려면 <p>
contenteditable div 안에 기본 텍스트 가있는 태그를 넣으십시오 .
예를 들어,
<div contenteditable></div>
사용하다:
<div contenteditable>
<p>Replace this text with something awesome!</p>
</div>
Chrome, Firefox 및 Edge에서 테스트되었으며 두 번째는 각각 동일하게 작동합니다.
먼저 그러나, 크롬으로 된 div를 생성 파이어 폭스에서 줄 바꿈을 생성하고, 가장자리에있는 div를 생성 하고 커서 대신 다음 하나에 이동 현재 DIV의 시작 부분에 다시 배치됩니다.
Chrome, Firefox 및 Edge에서 테스트되었습니다.
ckeditor를 사용해보십시오. 또한 SOF에서 이와 같은 형식을 제공합니다.
https://github.com/galetahub/ckeditor
<p>
예를 들어 div 대신 새 줄에 표시되는 예를 들어 태그로 단락을 줄 바꿈 할 수 있습니다. 예 :
<div contenteditable="true"><p>Line</p></div>
새 문자열을 삽입 한 후 :
<div contenteditable="true"><p>Line</p><p>New Line</p></div>
먼저 Enter 키를 눌렀는지 확인하기 위해 사용자가 입력 한 모든 키를 캡처해야합니다. 그런 다음 <div>
생성 을 막고 자체 <br>
태그를 만듭니다 .
하나의 문제가 있는데, 커서를 만들 때 커서가 같은 위치에 머무르기 때문에 Selection API 를 사용 하여 커서를 끝에 놓습니다.
<br>
텍스트의 끝에 태그 를 추가하는 것을 잊지 마십시오 . 첫 번째 입력을하지 않으면 새 줄을 만들지 않기 때문입니다.
$('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();
}
}
});
이것은 브라우저 지향 HTML5 편집기입니다. 로 텍스트를 감싸고 <p>...</p>
ENTER를 누를 때마다 얻을 수 <p></p>
있습니다. 또한 편집기는 SHIFT + ENTER를 누를 때마다 삽입되는 방식으로 작동합니다 <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>
이것을 확인하십시오 : http://jsfiddle.net/ZQztJ/
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>')
this
의미하는 실제 상황은 어디에 있습니까 document.getElementById('test');
?
inserHTML
명령 솔루션은 중첩이 이상한 것들을 않는 contenteditable
요소를.
I took some ideas from multiple answers here, and this seems to suit my needs for now:
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;
}
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();
}
});
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.
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/
I like to use Mousetrap for handlling hotkeys: https://craig.is/killing/mice
Then, I just intercept the enter event, executing a command insertLineBreak:
Mousetrap.bindGlobal('enter', (e)=>{
window.document.execCommand('insertLineBreak', false, null);
e.preventDefault();
});
All commands: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
It works using Chrome 75 and the following editable element:
<pre contenteditable="true"></pre>
It's also possible to use insertHTML:
window.document.execCommand('insertHTML', false, "\n");
It is possible to prevent this behaviour entirely.
$('<div class="temp-contenteditable-el" contenteditable="true"></div>').appendTo('body').focus().remove();
참고URL : https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
'IT story' 카테고리의 다른 글
컴파일 타임에 #define의 값을 어떻게 표시합니까? (0) | 2020.08.04 |
---|---|
DialogFragment에 인수 전달 (0) | 2020.08.04 |
위조 방지 토큰 문제 (MVC 5) (0) | 2020.08.04 |
버전이없는 버전의 Subversion 자동 제거 (0) | 2020.08.04 |
Java 또는 C #에서 다중 상속이 허용되지 않는 이유는 무엇입니까? (0) | 2020.08.04 |