使用javascript插入樣式,javascript插入樣式

來源:互聯網
上載者:User

使用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樣式的修改、添加及刪除的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.