2014-03-30 45 views
0

使用以下腳本,我將包含文本並在運行時將css插入到我的頁面頭部。但是,雖然插入的CSS不會影響。爲什麼?JavaScript將CSS插入頭部

(function() { 

    var styleEl = document.createElement("link"); 
    styleEl.type = "text/css"; 
    styleEl.href = "/static/css/widgets.css"; 
    //document.getElementsByTagName('head')[0].appendChild(styleEl); 
    document.head.appendChild(styleEl); 


    var foo = "Goodbye World!"; 
    document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>'); 
})(); 
+3

只是猜測,但嘗試添加rel =「樣式表」? –

+1

請勿使用'document.write'!請參閱[規範](http://www.w3.org/TR/html5/dom.html#document.write%28%29)中的警告。改用DOM方法。 – Oriol

+0

@Adrian Mitev,工作謝謝你!你想添加一個答案。 – Prometheus

回答

2

你忘了添加rel="stylesheet"這是聲明樣式<link>標籤很重要的。

這裏是更新的代碼與rel屬性的設置:

(function() { 
    var styleEl = document.createElement("link"); 
    styleEl.type = "text/css"; 
    styleEl.href = "/static/css/widgets.css"; 
    style.rel = "stylesheet"; 

    //document.getElementsByTagName('head')[0].appendChild(styleEl); 
    document.head.appendChild(styleEl); 


    var foo = "Goodbye World!"; 
    document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>'); 
})();