我正在制作一个在线Web编辑器,我需要这个。
如何将其设置为“另存为”功能而不是“下载功能”?区别在于,在“下载为”中,您不能确定应使用的名称,而在“另存为”中,可以在保存之前确定保存文件的名称。
那么,如何使它“另存为”而不是“另存为”?
PS:如果您也可以帮助我添加一个“加载文件”按钮,那也很好,那就太好了。
<html>
<head>
<style type="text/css">...</style>
<script type="text/JavaScript">
window.onload = function() {
var txt = document.getElementById('html');
txt.value = window.onload + '';
document.getElementById('link').onclick = function(code) {
this.href = 'data:text/plain;charset=utf-8,'
+ encodeURIComponent(html.value);
};
};
main();
</script>
</head>
<body>
<div id="txtWrap">
<textarea id="txt"></textarea>
</div>
<a href="" id="link" download="code.html">Download Above Code</a>
</body>
</html>
最佳答案
以下脚本利用了一些HTML5功能
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" cols="30" rows="7" class="form-control" placeholder="enter your text here!"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs" placeholder="example.txt" class="form-control"></td>
<td><button class="btn btn-primary" onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input class="form-control" type="file" id="fileToLoad"></td>
<td><button class="btn btn-primary" onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
关于javascript - 如何使它“另存为HTML”而不是“另存为HTML”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42569966/