Foo*_*eNG 8 javascript html5 textarea save
有人可以帮我将HTML5 textArea的内容保存到文件中,最好是使用JavaScript吗?
<textarea id="textArea">
Notes here...
</textarea>
<button type="button" value="save"> Save</button>
Run Code Online (Sandbox Code Playgroud)
eng*_*can 12
应该这样做.
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);
}
Run Code Online (Sandbox Code Playgroud)
#textArea {
display: block;
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<textarea id="textArea" rows="3">
Notes here...
</textarea>
<button type="button" value="save" id="save">Save</button>
Run Code Online (Sandbox Code Playgroud)
A-S*_*ani 11
答案中代码的简化版本:
function download(){
var text = document.getElementById("my-textarea").value;
text = text.replace(/\n/g, "\r\n"); // To retain the Line breaks.
var blob = new Blob([text], { type: "text/plain"});
var anchor = document.createElement("a");
anchor.download = "my-filename.txt";
anchor.href = window.URL.createObjectURL(blob);
anchor.target ="_blank";
anchor.style.display = "none"; // just to be safe!
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}
Run Code Online (Sandbox Code Playgroud)
和 html:
<textarea id="my-textarea">
Notes here...
</textarea>
<button type="button" onclick="download()">Save</button>
Run Code Online (Sandbox Code Playgroud)