2012-11-13 23 views
3

這在FF Safari和Chrome,但在IE8innerHTML的樣式元素導致運行錯誤

導致錯誤
var styleText = "#" + containerElement.id + " button {background-color:" + options.bg_color + ";}"; 
    styleText += "#" + containerElement.id + " button.not-open {color:" + options.txt_color + ";}"; 
    styleText += "#" + containerElement.id + " button.not-open:hover {color:" + options.hvr_color + ";}"; 
    styleText += ".info_pane {background-color:" + options.bg_color + ";}"; 
    styleText += ".info_pane {color:" + options.txt_color + ";}"; 
    styleText += ".info_pane a {color:" + options.txt_color + ";}"; 
    var style = document.createElement('style'); 
    style.type = 'text/css'; 
    style.innerHTML = styleText; 

的innerHTML是什麼引發錯誤的。做這項工作最好的選擇是什麼?我環顧四周,我發現的大部分東西似乎有點不穩定

+0

文件撰寫將是最好的選擇 –

+0

我試圖 \t \t文件撰寫(「<風格類型=」文本/ CSS「>'); \t \t document.write(styleText); \t \t document.write('');我該做什麼呢?這使得我的網頁上沒有任何東西出現haha –

回答

5

嘗試使用cssText屬性。 style.cssText = styleText;

編輯:顯然,那將是style.styleSheet.cssText = styleText;。我的錯。

DEMO

+0

演示不適合我... –

+0

我認爲這是行不通的,因爲'風格'對象是元素在我追加到我的文檔的頭上的頁面上。我不想改變「風格」元素 –

+0

的風格,沒有想到,想通了,發佈在下面 –

1
var styleText = "#" + containerElement.id + " button {background-color:" + options.bg_color + ";}"; 
    styleText += "#" + containerElement.id + " button.not-open {color:" + options.txt_color + ";}"; 
    styleText += "#" + containerElement.id + " button.not-open:hover {color:" + options.hvr_color + ";}"; 
    styleText += ".info_pane {background-color:" + options.bg_color + ";}"; 
    styleText += ".info_pane {color:" + options.txt_color + ";}"; 
    styleText += ".info_pane a {color:" + options.txt_color + ";}"; 
    var style = document.createElement('style'); 
    style.type = 'text/css'; 
    if(style.styleSheet) { //IE 
     style.styleSheet.cssText = styleText; 
     document.getElementsByTagName('head')[0].appendChild(style); 
    } else { 
     style.innerHTML = styleText; 
     document.getElementsByTagName('head')[0].appendChild(style); 
    } 

這是我最後不得不去。不記得我在哪裏找到它,但它的工作原理。

0

很高興你找到了一個解決方案......只是出於興趣,如果你嘗試以下任何一項,你會得到什麼?

style.innerText = styleText; 
style.insertAdjacentText('beforeEnd', styleText); 
style.insertAdjacentHTML('beforeEnd', styleText); 
style.replaceAdjacentText('beforeEnd', styleText); 

我目前無法訪問IE8用戶代理進行測試,只是在思考。根據msdn既不支持innerHTML,也不支持insertAdjacentHTMLStyle元素(相當可笑) ...但支持replaceAdjacentText?像往常一樣,好的舊IE。

我想另一個備用 - 只爲求思路 - 是使用:

var head = document.getElementsByTagName('head')[0]; 
    head.insertAdjacentHTML('<style>'+styleText+'</style>');