2016-03-16 52 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/

祝你好運;)