簡體   English   中英

如何從div獲取格式化文本?

[英]How to get formatted text from a div?

我正在創建一個文本編輯器。 現在,我停留在用戶單擊按鈕並將文本保存到文件(.txt)的位置:我可以從div獲取文本,但不能從格式化文本(從文本編輯器的工具欄獲取文本):-粗體,斜體等。通過execommand

如何實際做到這一點?

編輯

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

JavaScript:

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');
});

您可能需要將JavaScript的第二行更改為:

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

因此,您的完整JavaScript將是

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');
});

希望這會有所幫助。

除了在我嘗試使用的瀏覽器(Firefox,Chrome)中, .click()調用會靜默失敗的事實之外,該代碼的確會將HTML(不是純文本)發送到文件。

這是采用jQuery風格的代碼,其中包括使單擊生效的更改:

 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> 

在瀏覽器中打開下載頁面時,您會看到格式(粗體,顏色,字體)已正確應用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM