到目前为止,我已经有了一个由<textarea>
和CodeMirror.fromTextArea
组成的编辑器。
我可以写代码,而且运行起来非常棒,但是当我按CTRL+S时,它会显示一个对话框,用来保存HTML页面。我希望它能让我保存(下载)我输入的代码。
我已经成功绑定到save命令,如下所示:
CodeMirror.commands.save = function(editor) {
console.log("Yay!");
};
事实上,当我点击CTRL+S时,我会说“耶!”打印到控制台,不显示任何对话框。
现在,如何创建一个仅保存编辑器实例中的代码的保存对话框?
发布于 2018-07-13 06:27:24
假设您像这样初始化CodeMirror ..
var editor = CodeMirror.fromTextArea(document.getElementById('...'))...
然后,您可以根据自己的目的修改以下示例函数:
function saveTextAsFile() {
var textToWrite = editor.getValue();
var textFileAsBlob = new Blob([textToWrite], {
type: "text/plain;charset=utf-8"
});
var fileNameToSaveAs = "myfile.txt";
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();
}
祝好运!
https://stackoverflow.com/questions/51315044
复制相似问题