2014-02-18 126 views
3

你能幫我使用JavaScript來加載基於URL參數的CSS文件嗎?基於URL參數加載CSS文件

我有3個參數(一,二和三),我有3個CSS文件。

if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1) 
{ 
      What code should go in there to load the css? 
} 

JS應該保存在HTML文件的頭文件中嗎?

+0

這裏是一個例子的http://stackoverflow.com/a/577002/1113766 –

+0

可能重複[如何使用JavaScript來加載CSS文件?(HTTP://計算器.com/questions/574944/how-to-load-up-css-files-using-javascript) – apaul

回答

2
if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1) { 

    var $ = document; // shortcut 
    var cssId = 'myCss'; // you could encode the css path itself to generate id.. 
    if (!$.getElementById(cssId)) 
    { 
     var head = $.getElementsByTagName('head')[0]; 
     var link = $.createElement('link'); 
     link.id = cssId; 
     link.rel = 'stylesheet'; 
     link.type = 'text/css'; 
     link.href = 'css/one.css'; 
     link.media = 'all'; 
     head.appendChild(link); 
    } 

} 
else if(window.location.search.search(/[?&]parameter=two(?:$|&)/) !== -1) 
{ 
    //Another way & More simple 
    var ss = document.createElement("link"); 
    ss.type = "text/css"; 
    ss.rel = "stylesheet"; 
    ss.href = "css/two.css"; 
    document.getElementsByTagName("head")[0].appendChild(ss); 

} 

+0

謝謝,這是否必須在標題中? –

+0

它必須位於腳本標籤''您可以將'script'標籤放在'head'標籤內或體內。我認爲更好的標籤@CodyRaspien – AtanuCSE