微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 将HTML5 textarea内容保存到文件

有人可以帮我将 HTML5 textArea的内容保存到文件中,最好是使用 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

原文地址:https://www.jb51.cc/js/159069.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐