用javascript插入樣式


一、用javascript插入<style>樣式

有時候我們需要利用js來動態生成頁面上style標簽中的css代碼,方法很直接,就是直接創建一個style元素,然后設置style元素里面的css代碼,最后把它插入到head元素中。

但有些兼容性問題我們需要解決。首先在符合w3c標准的瀏覽器中我們只需要把要插入的css代碼作為一個文本節點插入到style元素中即可,而在IE中則需要利用style元素的styleSheet.cssText來解決。

還需要注意的就是在有些版本IE中一個頁面上style標簽數量是有限制的,如果超過了會報錯,需要考慮這點。

function addCSS(cssText){
    var style = document.createElement('style'),  //創建一個style元素
        head = document.head || document.getElementsByTagName('head')[0]; //獲取head元素
    style.type = 'text/css'; //這里必須顯示設置style元素的type屬性為text/css,否則在ie中不起作用
    if(style.styleSheet){ //IE
        var func = function(){
            try{ //防止IE中stylesheet數量超過限制而發生錯誤
                style.styleSheet.cssText = cssText;
            }catch(e){

            }
        }
        //如果當前styleSheet還不能用,則放到異步中則行
        if(style.styleSheet.disabled){
            setTimeout(func,10);
        }else{
            func();
        }
    }else{ //w3c
        //w3c瀏覽器中只要創建文本節點插入到style元素中就行了
        var textNode = document.createTextNode(cssText);
        style.appendChild(textNode);
    }
    head.appendChild(style); //把創建的style元素插入到head中    
}

//使用
addCSS('#demo{ height: 30px; background:#f00;}');

當然這只是一個最基本的演示方法,實際運用中還需進行完善,比如把每次生成的css代碼都插入到一個style元素中,這樣在IE中就不會發生stylesheet數量超出限制的錯誤了。

封裝:

var importStyle=function importStyle(b){var a=document.createElement("style"),c=document;c.getElementsByTagName("head")[0].appendChild(a);if(a.styleSheet){a.styleSheet.cssText=b}else{a.appendChild(c.createTextNode(b))}};
importStyle('h1 { background: red; }');//調用

seajs封裝

seajs.importStyle=function importStyle(b){var a=document.createElement("style"),c=document;c.getElementsByTagName("head")[0].appendChild(a);if(a.styleSheet){a.styleSheet.cssText=b}else{a.appendChild(c.createTextNode(b))}};

二、javascript插入<link>樣式

在<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.xxx.com/home/css/reset.css?v=20101227”);

 

參考:

http://www.cnblogs.com/2050/p/4029656.html

 

本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/5274781.html有問題歡迎與我討論,共同進步。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM