2016-10-02 4 views
1

텍스트 편집기를 만들고 있습니다. 이제 사용자가 버튼을 클릭하고 텍스트가 파일 (.txt)에 저장되는 지점에 갇혀 있습니다. div에서 텍스트를 가져올 수 있지만 텍스트 편집기의 툴바에서 서식이 지정된 텍스트는 없습니다. - 굵게 , 이탤릭체 등 .. execommand을 통해)div에서 형식이 지정된 텍스트를 가져 오는 방법은 무엇입니까?

실제로 어떻게 하는가?

편집

<div id="main"> 
    <span>Content of #main div goes here</span> 
</div> 
<a href="#" id="downloadLink">Download the inner html of #main</a> 

자바 스크립트 :

function downloadInnerHtml(filename, elId, mimeType) { 
    var elHtml = document.getElementById(elId).innerHTML; 
    var link = document.createElement('a'); 
    mimeType = mimeType || 'text/plain'; 
    link.setAttribute('download', filename); 
    link.setAttribute('href', 'data:' + mimeType+';charset=utf-8,'+ encodeURIComponent(elHtml)); 
    link.click(); 
} 
var fileName = 'tags.html'; // You can use the .txt extension if you want 
$('#downloadLink').click(function(){ 
    downloadInnerHtml(fileName, 'main','text/html'); 
}); 
+0

여기에 코드를 넣을 수 있습니까? – devendrant

+0

wysiwyg 편집기를 사용하는 경우 편집기 설명서 –

+0

을 읽으십시오. http://stackoverflow.com/help/how-to-ask.를 읽으십시오. – connexo

답변

2

외에도 .click() 전화, 내가 (파이어 폭스, 크롬)를 시도 브라우저에 자동으로이 파일에 HTML (안 일반 텍스트)를 전송 않는 코드 실패는 사실에서.

function downloadInnerHtml(filename, elId, mimeType) { 
 
    var elHtml = $('#' + elId).html(); 
 
    mimeType = mimeType || 'text/plain'; 
 
    $('<a>').attr('download', filename) 
 
      .attr('href', 'data:' + mimeType+';charset=utf-8,'+ encodeURIComponent(elHtml)) 
 
      .get(0) 
 
      .dispatchEvent(new MouseEvent("click")); 
 
} 
 
var fileName = 'tags.html'; 
 
$('#downloadLink').click(function(){ 
 
    downloadInnerHtml(fileName, 'main','text/html'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main"> 
 
    <span>Content of <b>#main</b> <span style="font-family:Courier New">div</span> goes <font color="red">here</font></span> 
 
</div> 
 
<a href="#" id="downloadLink">Download the inner html of #main</a>

브라우저 내부의 다운로드 페이지를 열고, 당신이 나타납니다 : 여기

은 클릭 작업을 할 수있는 변화를 포함하여, 더 jQuery를 스타일 코드입니다 서식 (굵게, 색, 글꼴)이 올바르게 적용됩니다.

+0

잘 @trincot, 포맷 작업 .html로 완벽하게하지만 .txt 형식으로 HTML 태그를 보여줍니다. – chitrank

+0

여러분을 환영합니다! .txt 파일에 대한 주석을 삭제했습니다. – trincot

3

당신은 자바 스크립트의 2 선을 변경해야 할 수도 있습니다 :

var elHtml = $("#"+elId).html(); 

그래서 완전한 자바 스크립트가 될 것입니다

function downloadInnerHtml(filename, elId, mimeType) { 
    var elHtml = $("#"+elId).html(); 
    var link = document.createElement('a'); 
    mimeType = mimeType || 'text/plain'; 
    link.setAttribute('download', filename); 
    link.setAttribute('href', 'data:' + mimeType+';charset=utf-8,'+ encodeURIComponent(elHtml)); 
    link.click(); 
} 
var fileName = 'tags.html'; // You can use the .txt extension if you want 
$('#downloadLink').click(function(){ 
    downloadInnerHtml(fileName, 'main','text/html'); 
}); 

희망이 도움이 될 것입니다.

+0

원래 코드가 잘못된 이유를 설명 할 수 있습니까? 내가 알 수있는 한, 그들은 동등합니다. – trincot

관련 문제