深入理解指令碼化CSS系列第五篇——動態樣式

來源:互聯網
上載者:User

標籤:

前面的話

  很多時候,DOM操作比較簡單明了,因此用javascript產生那些通常原本是HTML代碼產生的內容並不麻煩。但由於瀏覽器充斥著隱藏的陷阱和不相容問題,處理DOM中的某些部分時要複雜一些,比如動態樣式就相對較複雜

  所謂動態樣式,是指在頁面載入時並不存在,在頁面載入完成後動態添加到頁面的樣式

  動態樣式包括兩種情況:一種是通過<link>元素插入外部樣式表,另一種是通過<style>元素插入內部樣式。下面將詳細介紹這兩種情況

 

外部樣式
/*style.css裡面的內容*/.box{height:100px;width:100px;background-color: pink;}
var link = document.createElement("link");link.rel = "stylesheet";link.type = "text/css";link.href = "style.css";var head = document.getElementsByTagName(‘head‘)[0];head.appendChild(link);

  使用函數封裝如下:

<div class="box">測試文字</div><button id="btn">動態添加樣式</button><script>function loadStyles(url){    loadStyles.mark = ‘load‘;    var link = document.createElement("link");    link.rel = "stylesheet";    link.type = "text/css";    link.href = url;    var head = document.getElementsByTagName(‘head‘)[0];    head.appendChild(link); }btn.onclick = function(){    if(loadStyles.mark != ‘load‘){        loadStyles("style.css");            }}</script>

內部樣式
var style = document.createElement("style");style.type = "text/css";style.innerHTML = ".box{height:100px;width:100px;background-color: pink;}";var head = document.getElementsByTagName(‘head‘)[0];head.appendChild(style); 

  使用函數封裝如下:

<div class="box">測試文字</div><button id="btn">動態添加樣式</button><script>function loadStyles(str){    loadStyles.mark = ‘load‘;    var style = document.createElement("style");    style.type = "text/css";    style.innerHTML = str;    var head = document.getElementsByTagName(‘head‘)[0];    head.appendChild(style); }btn.onclick = function(){    if(loadStyles.mark != ‘load‘){        loadStyles(".box{height:100px;width:100px;background-color: pink;}");            }}</script>

  [注意]該方法在IE8-瀏覽器中報錯,因為IE8-瀏覽器將<style>視為當作特殊的節點,不允許訪問其子節點或設定innerHTML 屬性

相容

  IE瀏覽器支援訪問並修改元素的CSSStyleSheet對象的cssText屬性,通過修改該屬性可實作類別似效果

<div class="box">測試文字</div><button id="btn">動態添加樣式</button><script>function loadStyles(str){    loadStyles.mark = ‘load‘;    var style = document.createElement("style");    style.type = "text/css";    try{        style.innerHTML = str;    }catch(ex){        style.styleSheet.cssText = str;    }    var head = document.getElementsByTagName(‘head‘)[0];    head.appendChild(style); }btn.onclick = function(){    if(loadStyles.mark != ‘load‘){        loadStyles(".box{height:100px;width:100px;background-color: pink;}");            }}</script>    

 

深入理解指令碼化CSS系列第五篇——動態樣式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.