DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript插入樣式實現代碼
javascript插入樣式實現代碼
編輯:關於JavaScript     
javascript插入樣式在前端開發中應用比較廣泛,特別是在修改前端表現和頁面換膚的時候。最近做的這個任務是用戶在別人的站點上點擊一個按鈕,就會在別的站點頁面下插入一個腳本,執行,這其中包含了樣式的插入。

一般情況下javascript動態插入樣式有兩種,一種頁面中引入外部樣式,在<head>中使用<link>標簽引入一個外部樣式文件,另一種是在頁面中使用<style>標簽插入頁面樣式(這裡說的不是style屬性)。
一、頁面中引入外部樣式:
在<head>中使用<link>標簽引入一個外部樣式文件,這個比較簡單,各個主流浏覽器也不存在兼容性問題:
復制代碼 代碼如下:
function includeLinkStyle(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
includeLinkStyle("http://css.jb51.net/home/css/reset.css?v=20101227");

但是在我目前做的這個項目中本身應用的樣式非常少,直接用引入一個外部樣式文件似乎不合適,所以我選擇了第二種方案,在頁面中使用<style>標簽插入頁面樣式。
二、使用<style>標簽插入頁面樣式:
這種方式在各個主流浏覽器存在兼容性問題,像firefox等標准浏覽器無法直接獲取設置styleSheet的cssText值,標准浏覽器下只能使用document.styleSheets[0].cssRules[0].cssText單個獲取樣式;同時使用:document.styleSheets[0].cssRules[0].cssText=newcssText;頁面不會自動更新樣式,必須使用:document.styleSheets[0].cssRules[0].style.cssText=newcssText;這點似乎沒坑爹的IE來的人性化和簡便。YUI中使用了一個很好的辦法:style.appendChild(document.createTextNode(styles));采用createTextNode將樣式字符串添加到<style>標簽內;
復制代碼 代碼如下:
function includeStyleElement(styles,styleId) {
if (document.getElementById(styleId)) {
return
}
var style = document.createElement("style");
style.id = styleId;
//這裡最好給ie設置下面的屬性
/*if (isIE()) {
style.type = "text/css";
style.media = "screen"
}*/
(document.getElementsByTagName("head")[0] || document.body).appendChild(style);
if (style.styleSheet) { //for ie
style.styleSheet.cssText = styles;
} else {//for w3c
style.appendChild(document.createTextNode(styles));
}
}
var styles = "#div{background-color: #FF3300; color:#FFFFFF }";
includeStyleElement(styles,"newstyle");

這樣頁面中的元素就能直接應用樣式了,不管你的這些元素是不是通過腳本追加的。
關於手賤:
看這段代碼:
復制代碼 代碼如下:
var divObj = document.createElement("div");
divObj .id = "__div";
divObj .innerHTML="測試js插入DOM和樣式";
document.body.appendChild(divObj );
var styles = "#__div{background-color: #FF3300; color:#FFFFFF }";
includeStyleElement(styles,"newstyle");

前面說了這個項目是用戶在別人的站點上點擊一個按鈕,就會在別的站點頁面下插入一個腳本,執行,這其中包含了樣式的插入,我為了盡可能的保證我創建的元素ID唯一性,手賤在元素ID前加了“__”,表示私有防止沖突。結果悲劇了,IE6,IE7 class和id的命名不能以下劃線開頭(“_”),竟然把這個給忘了!花了兩個小時才找到原因。悲劇啊!得出一個結論!
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved