到目前为止,我有一个由<textarea>
和CodeMirror.fromTextArea
组成的编辑器。
我可以编写代码,并且效果很棒,但是当我按CTRL + S时,会显示一个对话框来保存HTML页面。我希望它可以让我保存(下载)键入的代码。
我已成功绑定到save命令,如下所示:
CodeMirror.commands.save = function(editor) {
console.log("Yay!");
};
实际上,当我按CTRL + S时,我表示“是!”。打印到控制台,没有对话框显示。
现在,如何创建一个仅在编辑器实例中保存代码的保存对话框?
答案 0 :(得分:1)
假设您这样初始化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();
}
祝你好运!