【问题标题】:Download a dynamically created CSS file generated by Javascript下载由 Javascript 生成的动态创建的 CSS 文件
【发布时间】:2016-03-16 13:06:57
【问题描述】:

我在这里无数次搜索我的项目帮助,现在我终于创建了一个帐户。我希望对我发现的一个类似问题的答案有所澄清,该问题的功能与我想要的相似。我本质上希望用户单击一个按钮并下载一个 CSS 文件,其中包含使用 JavaScript 推送到一个空数组的数据。

这是我发现在一定程度上有效的代码(我在实际代码中点击触发了该功能,但这部分是我遇到问题的特定区域。)

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    pom.dispatchEvent(event);
}
else {
    pom.click();
}
}

download('responsive.css', 'Hello world!');

我发现这在 Chrome 中运行良好,但是当我让其他人在 Firefox 中测试它时,它被下载为 responsive.css.txt 。我做了一些研究,看看是否可以在我的代码的第 3 行中将“data:text/plain”更改为“data:text/css”,但我的测试人员告诉我他仍然遇到同样的问题。此外,如果有人有一个解决方案可以在 IE 中运行,那就太好了,因为现在当您单击按钮下载时,什么也没有发生。

提前致谢!

【问题讨论】:

标签: javascript css download data-uri


【解决方案1】:

如果您将类型设置为下载,它应该可以工作:

function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute(
    'href',
    'data:application/download;charset=utf-8,' + encodeURIComponent(text)
  );
  pom.setAttribute('download', filename);

  if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    pom.dispatchEvent(event);
  }
  else {
    pom.click();
  }
}

download('responsive.css', 'Hello world!');

见:https://jsfiddle.net/s5on5dau/1/

祝你好运;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多