使用javascript插入樣式,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”);
以上就是本文的全部內容,希望對大家的學習有所協助。
您可能感興趣的文章:
- javascript插入樣式實現代碼
- JavaScript插入動態樣式實現代碼
- ExtJS自訂佈景主題(theme)樣式詳解
- jsp頁面中插入css樣式的三種方法總結
- js動態修改整個頁面樣式達到換膚效果
- jquery mobile頁面跳轉後樣式丟失js失效的解決方案
- 點擊button擷取text內容並改變樣式的js實現
- js實現class樣式的修改、添加及刪除的方法