2014-12-16 4 views
2

contenteditable = 'true'div에서 서식이 지정된 텍스트를 가져 와서 내 서버로 보내려고합니다.div에서 올바르게 형식화 된 텍스트 값을 가져 오는 방법

텍스트 영역을 사용하는 경우 텍스트 영역의 값을 가져올 때 공백과 줄 바꿈을 유지하지만 다음과 같은 스타일을 사용하는 경우에도 contentedit div를 사용하면 올바른 형식의 텍스트를 얻을 수 없습니다. 예를 들어

white-space: pre-wrap; 
word-wrap: break-word; 

내 사업부에이를 입력하면 :

"a 
aa 

asdf" 

내가는 TextContent와이를 얻을 것이다 :

"a aaasdf" 

texteda와 같이 contenteditable div에서 형식이 지정된 텍스트를 가져 오는 방법이 있습니까?

+0

코드 어디에 있습니까? – JLRishe

+1

사용해보기.innerText –

+0

@Derek : 아래에서 해답을 찾아 문제를 해결하는 것으로 표시된 하나를 표시하십시오. –

답변

5

줄 바꿈도 사용하려면 .innerHTML을 사용하십시오.

Readup : .innerHTML | MDN

작업 코드 조각 :

document.getElementById('copy').addEventListener('click', function(){ 
 
    var text = document.getElementById('input').innerHTML; 
 
    document.getElementById('output').innerHTML = text; 
 
});
div{ 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid black; 
 
    display: inline-block; 
 
    vertical-align: top; 
 
}
<div contenteditable='true' id="input">Enter something funny<br>;)</div> 
 

 
<button id="copy">Copy Text</button> 
 

 
<div id="output">Text will be copied here.</div>

+1

.innerHTML은 < br >과 함께 모든 내부 HTML을 반환합니다. 대신 .innerText를 사용해야합니다. –

+0

@Alexander 지적 해 주셔서 감사합니다! 나는 나의 대답을 업데이트했다. :) –

+0

예, 크롬에서는 훌륭하지만 Firefox에서는 innerText가 작동하지 않습니다. 크로스 브라우저 솔루션을 알고 있습니까? – Derek

2

예에서 : Extracting text from a contentEditable div

function getContentEditableText(id) { 
    var ce = $("<pre />").html($("#" + id).html()); 
    if ($.browser.webkit) 
     ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; }); 
    if ($.browser.msie) 
     ce.find("p").replaceWith(function() { return this.innerHTML + "<br>"; }); 
    if ($.browser.mozilla || $.browser.opera || $.browser.msie) 
     ce.find("br").replaceWith("\n"); 

    return ce.text(); 
} 

또는

$.fn.getPreText = function() { 
    var ce = $("<pre />").html(this.html()); 
    if ($.browser.webkit) 
     ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; }); 
    if ($.browser.msie) 
     ce.find("p").replaceWith(function() { return this.innerHTML + "<br>"; }); 
    if ($.browser.mozilla || $.browser.opera || $.browser.msie) 
     ce.find("br").replaceWith("\n"); 

    return ce.text(); 
}; 

이 경우 jQuery가 필요합니다.

1

contenteditable 요소에 내용을 입력하면 대상 요소 내에 HTML 노드가 자동으로 생성됩니다. 은 그래서 당신은이 아닌 일반 텍스트를 그 .innerHTML 속성에 액세스하고 HTML 등의 내용을 처리 할 필요가

당신은 .innerHTML 속성을 사용하여이 HTML 콘텐츠에 액세스하거나 일반 텍스트를 반환하지만 같은 서식을 유지 .innerText을 사용할 수 있습니다 @Rahul 데 사이의 대답과 this blog post에 표시 :

document.getElementById('getText').onclick = function() { 
 
    console.log(document.getElementById('edit').innerHTML); 
 
};
<div id='edit' contenteditable='true'>Type here</div> 
 
<input id='getText' type='button' value='Get Text' />

내가

를 입력하면

안녕하세요


가 사업부에 당신

을하고 다음 버튼을 클릭하는 방법, 콘솔 보여줍니다

<p>Hello</p><p>how</p><p><br></p><p>are you</p> 
관련 문제