javascript - 将 HTML5 文本区域内容保存到文件

标签 javascript html save 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 = "file.txt"; //filename.extension

  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

关于javascript - 将 HTML5 文本区域内容保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21479107/

相关文章:

javascript - 如何根据 jquery 中的过滤器禁用和启用列表项?

html - 为什么对我网站上的某些图像应用了一个奇怪的类?

jquery - 从 JQuery 文件夹中选择随机图像文件

html - 为什么 H2 比 H1 大?

python - 在 Python 中保存文件时,我应该将连接的文件路径放在哪里?

android - 文件未保存在 Android 中

java - 有没有更好的方法...(Java,保存数据)

javascript - 在 fabric.js 中更改双指缩放灵敏度

javascript - 如何使用 angularjs 一次添加多个图像

javascript - 检查字符串是否包含 'abc' 或 'cde' 开 Jest