DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
用 JavaScript 動態建立 style 節點
編輯:CSS進階教程     

網路上動態建立 style 節點的方法不少,但大多只談外部 CSS 檔的載入。如何用程式產生的字串直接建立 style 節點,我折騰了兩個小時,這裡把過程與結論記錄下來。

靜態引入外部 CSS

@import url(style.css);

動態載入外部 CSS 的兩種寫法

第一種是建立 link 元素:

var style = document.createElement('link');
style.href = 'style.css';
style.rel = 'stylesheet';
style.type = 'text/css';
document.getElementsByTagName('HEAD').item(0).appendChild(style);

第二種更短,IE 專用:

document.createStyleSheet('style.css');

用字串直接建立 style 節點

標準寫法如下:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML="body{ background-color:blue; }";
document.getElementsByTagName('HEAD').item(0).appendChild(style);

很遺憾,這段在 Firefox 裡正常,IE 卻不支援。論壇上的替代方案是:

var sheet = document.createStyleSheet();
sheet.addRule('body','background-color:red');

可以動,但很麻煩:字串必須拆成選擇器與宣告兩部分,規則一長就很難寫。

繞過 URL 長度限制

後來找到一個寫法:

document.createStyleSheet("javascript:'body{background-color:blue;'");

行得通,但 URL 最長 255 字元,樣式稍長就掰掉。經 SXPCrazy 提示,改成先把樣式字串放進全域變數,再傳入變數名稱,就完美解決了:

window.style="body{background-color:blue;";
document.createStyleSheet("javascript:style");

完整範例

<html>
<head>
<script>
function blue(){
if(document.all){
window.style="body{background-color:blue;";
document.createStyleSheet("javascript:style");
}else{
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML="body{ background-color:blue }";
document.getElementsByTagName('HEAD').item(0).appendChild(style);
}
}
</script>
</head>
<body>
<input type="button" value="blue" onclick="blue();" />
</body>
</html>

用 document.all 判斷是否為 IE,再分別走兩條路徑,就能兼顧兩邊。今天只要統一用標準的 createElement 寫法即可,這段歷史純供理解。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved