将HTML5 textarea内容保存到文件 [英] Saving HTML5 textarea contents to file

查看:731
本文介绍了将HTML5 textarea内容保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我将HTML5 textArea的内容保存到文件中,最好是使用JavaScript吗?

Could someone help me save the contents of a HTML5 textArea to file, preferably using JavaScript?

<textarea id="textArea">
   Notes here...
</textarea>
<button type="button" value="save"> Save</button>


推荐答案

应该这样做。

function saveTextAsFile() {
  var textToWrite = document.getElementById('textArea').innerHTML;
  var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
  var fileNameToSaveAs = "ecc.plist";

  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "Download File";
  if (window.webkitURL != null) {
    // Chrome allows the link to be clicked without actually adding it to the DOM.
    downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  } else {
    // Firefox requires the link to be added to the DOM before it can be clicked.
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
  }

  downloadLink.click();
}

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);

function destroyClickedElement(event) {
  // remove the link from the DOM
  document.body.removeChild(event.target);
}

#textArea {
  display: block;
  width: 100%;
}

<textarea id="textArea" rows="3">
   Notes here...
</textarea>
<button type="button" value="save" id="save">Save</button>

JSFiddle

这篇关于将HTML5 textarea内容保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆