2016-03-16 53 views
0

我在这里搜索了无数次在我的项目中寻求帮助,现在我终于创建了一个帐户。我希望得到一些解释,我发现一个类似于我想要的功能的类似问题的答案。我基本上希望用户点击一个按钮并下载一个CSS文件,其中的数据通过JavaScript被推送到一个空的数组中。下载由Javascript生成的动态创建的CSS文件

这里是我发现的代码工作在一定程度上(我已经触发点击功能我实际的代码中,但这块是我在遇到麻烦的特定区域。)

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浏览器中运行,这将是很好的,因为现在当你点击按钮下载没有任何反应。

在此先感谢!

+0

您必须将元素添加到DOM。 https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild – NatureShade

回答

0

,如果你设置下载类型,它应该工作:

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/

祝你好运;)