標籤:
前面的話
很多時候,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系列第五篇——動態樣式