나는 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/>');
// 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;
}
답변
스타일을 추가 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;
});
답변
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