如何从div获取格式化文本?

时间:2016-10-02 05:58:48

标签: javascript jquery html css

我正在创建一个文本编辑器。现在我陷入了用户单击按钮并将文本保存到文件(.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');
});

2 个答案:

答案 0 :(得分:3)

您可能需要将第二行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');
});

希望这会有所帮助。

答案 1 :(得分:2)

除了在我尝试过的浏览器(Firefox,Chrome)中.click()调用无声地失败之外,代码 发送HTML(不是纯文本)到文件。

以下是更多jQuery样式的代码,包括使点击工作的更改:

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

在浏览器中打开下载页面时,您会看到正确应用格式(粗体,颜色,字体)。