【问题标题】:How do I save the content of the editor, not the whole HTML page?如何保存编辑器的内容,而不是整个 HTML 页面?
【发布时间】:2018-12-21 05:45:32
【问题描述】:

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

我可以编写代码,而且效果非常好,但是当我按下 CTRL+S 时,它会显示一个对话框来保存 HTML 页面。我希望它可以让我保存(下载)我输入的代码。

我已经成功绑定到save命令如下:

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

确实,当我按下 CTRL+S 时,我听到“耶!”打印到控制台并且不显示任何对话框。

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

【问题讨论】:

标签: javascript codemirror


【解决方案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();
}

祝你好运!

【讨论】:

  • 不错的解决方案。适用于 Firefox、Chrome 和 adblock。我在 Edge 上试过,它也可以。我在IE11上测试过,完全不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多