如何保存编辑器的内容,而不是整个HTML页面



到目前为止,我有一个由<textarea>CodeMirror.fromTextArea组成的编辑器。

我可以写代码,它的工作原理很好,但当我按下CTRL+S时,它会显示一个对话框来保存HTML页面。我希望它能让我保存(下载(我键入的代码。

我已成功绑定到保存命令,如下所示:

CodeMirror.commands.save = function(editor) {
console.log("Yay!");
};

事实上,当我按下CTRL+S时,我在控制台上打印了"耶!",并且没有显示任何对话框。

现在,我如何创建一个保存对话框,只保存编辑器实例中的代码?

假设您像这样初始化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();
}

祝你好运!

最新更新