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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/js/159069.html

猜你在找的JavaScript相关文章