DOM Style樣式對象的詳細用法
HTML Style樣式比較復雜,相應訪問、修改方法也有所差異。參考相關資料,整理如下。
典型Html文件如下,有三種定義方式。
<head> |
<style type="text/css"> |
/* 內部樣式 */ |
h3 {color:green;} |
</style> |
<!-- 外部樣式 style.css --> |
<link rel="stylesheet" type="text/css" href="style.css"/> |
<!-- 在外部的styles.css文件中,代碼如下: |
h3 {color:blue;} --> |
</head> |
<body> |
<h3 style ="color:Black;" >測試!</h3> |
</body> |
定義1:行內樣式, (內聯樣式)Inline style
任何HTML元素標簽都會有一個通用的屬性style。它會返回CSSStyleDeclaration對象。
樣式定義在HTML元素的標准屬性style里
a 將分號『;』隔開的一個或者多個屬性:值(其全部為元素的style屬性的值)
b 屬性和屬性值之間用 『:』連接
下面我們看幾個最常見的行內style樣式的訪問方式。Style在元素節點內,style可讀可寫;
<div id='St1' style="font-family:Arial,Helvetica;width:100px; height:100px; color:red;">芒果</div>
var oV1 = document.getElementById('St1')
a)獲取:x = oV1.Style.width
x = oV1.Style.getPropertyValue('height')
b)設置:oV1.style.backgroundColor = 'red';
oV1.Style.setProperty('height', '200px')
c)移出(2種):oV1.style.font-family="";
oV1.style.removeProperty("background-color")
d)所有內聯樣式 CSS 屬性
style樣式是個 CSSStyleDeclaration 對象,它不僅提供了單個 CSS 屬性的訪問方式,如cssText屬性 ,也提供 setProperty()、getPropertyValue()及removeProperty() 方法
oV1.Style.cssText = "background-color:red; height:200px; width: 200px"
oV1.Style.cssText = '';
oV1.setAttribute('style', 'background-color:blue; height:100px; width:100px');
oV1.getAttribute('style');
oV1.removeAttribute('style');
僅能操作style屬性中定義的內聯樣式,無法獲取或設置樣式表中的樣式
定義2:內部樣式表(style元素) Internal style sheet
其使用 <style> 標記將樣式定義為內部塊對象,內部樣式只對所在的網頁有效。
示例代碼如下: 嵌入 CSS 可以有效減少 HTTP 請求,提升頁面性能
<head>
<style type="text/css">
<!--
//div(選擇器) {width: 100px;(樣式聲明) }
div,h3 { background-color: black; width: 100px; } //兩個標簽選擇符
#Id1 { width: 100px; height: 100px; background-color: red; } //一個id選擇符
.c3 { color:blue;} //class選擇符
p.cla4 { color:#fff; background:#070;} /* 一個元素、一個class選擇符
-->
</style>
<style type="text/css"> @import url(sty2.css); </style> //導入式
<link rel="stylesheet" type="text/css" href="wider.css"> //外部鏈接式(rel,type不要動)
</head>
//wider.css中的定義 #box { width: 200px; }
function getStyle(oDiv, attr){
if (oDiv.currentStyle) {return oDiv.currentStyle[attr]; //針對IE瀏覽器 }
else {return getComputedStyle(oDiv, false)[attr]; } //Firefox瀏覽器
}
<div id="id1" class="c3" >test style</div>
var oT1 = document.getElementById('id1');
var a = getStyle(oT1, 'width');
使用style屬性可以設置行內的CSS樣式,而通過id和class調用時最常用的方法。
CSSStyleSheet類型表示通過<link>元素(HTMLLinkElement對象)和<style>元素(HTMLStyleElement對象)包含的樣式表。
樣式表中一個大括號就是一個cssRule對象
var sheet=link.sheet||link.styleSheet; //(非IE)使用sheet屬性,(IE)使用styleSheet得到這個類型
var sheet=document.styleSheets[i]; //styleSheets: 獲得當前網頁的所有樣式表對象
定義3:外部樣式表(引用一個CSS樣式表文件)Rules或rules
(1) DOM(document對象)對象模型中有幾個重要的集合
doc1.images [HTMLCollection] 所有圖像
doc1.anchors [HTMLCollection] 所有錨點
doc1.styleSheets [StyleSheetList] 所有樣式
doc1.links [HTMLCollection] 所有鏈接
其中styleSheets包含所有的樣式集合
(2) 樣式表集合styleSheets -> 規則(選擇器及樣式)(css)rules ->某一樣式.屬性 style.attr
一個style元素標簽(一個樣式表) var sheet=document.styleSheets[0]
規則集合(選擇器及樣式集合) vsr Rules =sheet.cssRules||sheet[0].rules; //W3C用cssRules //微軟rules
第一個規則(選擇器及樣式) var rule=doc1.styleSheets[0].rules[0] //rules[0](IE),CSSRules[0](非IE)
var rule=sheet.cssRules[0]|| sheet.rules[0];
style標簽或單個Style的全部內容 head.style.cssText, oV1.style.cssText 或 rules[0].style.cssText
style標簽中一個大括號就是一個(css)Rule對象,cssRules(非IE)|rules(IE)可返回某一樣式表中全部選擇器的集合列表,可以通過CSSRules[0](非IE)和rules[0]屬性(IE)來進行訪問。第一條規則就是(css)Rules[0],第二條就是(css)Rules[1]等等。
一條規則就是一個元素的聲明 p {background-color: #ffffff;} 或者多個元素的一組聲明 div,h3,p{color:blue;width: 100px;} (IE還將其分為3條)。可以對每個樣式進行具體的操作(可讀可寫)。
通過 className 修改樣式 , 獲取或修改某個屬性的值(兼容性問題)
doc1.styleSheets[0].(css)rules[index].style.attr //IE,W3C為(css),查找樣式表中的樣式屬性(ie chrom)
(3) style樣式,規則(css)rules在各瀏覽器中差異
例:下列樣式表在不同瀏覽器的解釋
@import url("test.css"); p,h2,h3 {padding-right: 10px; } pre.test + * {margin-right: 20%; } pre.test {background-color: #ffffff; } |
|
Safari看見的是【4條】規則: 注意大寫 cssRules[0]、undefined cssRules[1]、P cssRules[2]、PRE.test[CLASSS~="test"]+* cssRules[3]、PRE.test[CLASSS~="test"] Safari則只取p。我才知道這是一種不正確的寫法 |
IE7看見了【5條】: 注意大寫 rules[0]、P rules[1]、H2 rules[2]、H3 rules[3]、PRE.test + * rules[4]、PRE.test IE認為p,h2,h3是三條而不是一條規則, |
Mozilla和Opera 9看見4條: 注意小寫 cssRules[0]、undefined cssRules[1]、p,h2,h3 cssRules[2]、pre.test + * cssRules[3]、pre.test |
Mac IE也看見5條: 注意大寫 0、P 1、H2 2、H3 3、PRE.test * (注意沒有+號) 4、PRE.test Mac IE把選擇器改成了pre.test *, |
所以要訪問pre.test在Safari和Mozilla里需要cssRules[3],而IE是rules[4],早期的Mozilla是cssRules[5]。
沒有關鍵字 ,所以如果使用索引值的話問題就非常嚴重。
我們希望能這樣訪問: document.styleSheets[1].cssRules['PRE.test'],這樣我就能訪問pre的樣式表規則了。但是W3C或者其他瀏覽器貌似不需要這樣的訪問樣式表的方法。但是所有的文檔在這個問題上都保持沉默。
這個失敗意味着你基本上沒法訪問規則了。
假設我們已經訪問了一條規則。現在需要改變其中一條聲明。
(1)表達式如下: rule.style.color = '#0000cc';
(2)W3C的方法是: rule.style.setProperty('color','#00cc00',null);因為style.color簡單的多,所以我不想用這個。
例子:打算改變pre的顏色,代碼如下:
為了保證能用,我把pre的規則寫在最后一條。很丑,但是這是唯一的辦法:
function changeIt() {
if (!document.styleSheets) return;
var theRules = new Array();
if (document.styleSheets[1].cssRules) theRules = document.styleSheets[1].cssRules
else if (document.styleSheets[1].rules) theRules = document.styleSheets[1].rules
else return;
theRules[theRules.length-1].style.backgroundColor = '#EEF0F5';
}
(4) style樣式的添加或刪除
doc1.styleSheets[0].insertRule(“selector{attr:value}”, index); //非IE
doc1.styleSheets[0].deleteRule(index); //非IE
doc1.styleSheets[0].addRule(“selector”,”attr:value”, index); //IE
doc1.styleSheets[0].removeRule(index); //IE
a) 插入函數
function insertRule(sheet,selectorText,cssText,position){
if(sheet.insertRule){ sheet.insertRule(selectorText+'{'+cssText+'}',position); }
else if(sheet.addRule){ sheet.addRule(selectorText,cssText,position); }
b) 刪除函數
function deleteRule(sheet,position){
if (sheet.deleteRule) sheet.deleteRule(position); //非IE ,假設這樣的方式存在
else if(sheet.removeRule){ sheet.removeRule(position); }
c) 賦值,改動CSS樣式
rules[0].style.color='green'; //鏈接CSS樣式中改動詳細的屬性
oDiv1.style.color='blue'; //行內樣式
4 單個操作 或 批量操作
a) 某元素Style屬性的單個操作
obj.style.backgroundColor="red"; //注意,如果原來樣式中有-,需要去掉,然后將后面的單詞首字母大寫
b) 某元素Style屬性的批量操作
不僅有單個 CSS 屬性的訪問方式,如cssText屬性
doc1.head.style.csstext="h3 {color:green;}" //網頁的Style元素結點內容的修改
oV1.Style.cssText = "background-color:red; height:200px; width: 200px"
oV1.setAttribute('style', 'background-color:blue; height:100px; width:100px');
oV1.removeAttribute('style');
obj.style="height:500px;color:red;"; //直接設置style對象,注意style的格式
obj.className="test"; //指定obj的className屬性,給它類選擇器名
obj.className="test demo"; //使用className設置屬性 //注意空格 ,可以指定多個類
obj.className=""; //刪除樣式
5 多重樣式的計算(Multiple Styles):
由於外部樣式、內部樣式和行內樣式可能同時作用於某一個元素,此外如DIV,P等元素內部還可能有子元素節點而產生的樣式嵌套現象,於是就有了多重樣式。
此種情況下,樣式就有了優先級,一般(行內)Inline style > (內部樣式)Internal style sheet >(Css外部樣式)External style sheet。有一套比較復雜的計算優先級的方法。
有個例外的情況,就是如果外部樣式放在內部樣式的后面,則外部樣式將覆蓋內部樣式。
對於多種樣式的復合情況下真實的樣式信息,就需要通過計算,來獲得樣式,即計算樣式(當然也就只讀了)。
(非IE)window對象下提供了getComputedStyle()方法。接受兩個參數,需要計算的樣式元素,第二個偽類(:hover),如果沒有偽類,就填null。 window.getComputedStyle 還有另一種寫法,就是 document.defaultView.getComputedStyle 。
(IE)使用 currentStyle 屬性,IE 中使用 getAttribute 。currentStyle 要獲得屬性名的話必須采用駝峰式的寫法。也就是如果我需要獲取 font-size 屬性,那么傳入的參數應該是 fontSize。因此在IE 中要獲得單個屬性的值,就必須將屬性名轉為駝峰形式。
// IE 下將 CSS 命名轉換為駝峰表示法 // font-size --> fontSize // 利用正則處理一下就可以了 function camelize(attr) { // /\-(\w)/g 正則內的 (\w) 是一個捕獲,捕獲的內容對應后面 function 的 letter // 意思是將 匹配到的 -x 結構的 x 轉換為大寫的 X (x 這里代表任意字母) return attr.replace(/\-(\w)/g, function(all, letter) { return letter.toUpperCase();}); } element.currentStyle.getAttribute(camelize(style)); // 獲取元素 element 的 style 屬性樣式 |
<style type="text/css"> <!-- div { background-color: black; width: 100px; } #id3{ width: 100px; height: 100px; background-color: red; }
--> function getStyle(oDiv, attr) var test = document.getElementById('id3'); //得到某元素的樣式 |
獲取最終樣式(只能獲取,不能操作)
oDiv1.currentStyle.attr // ( IE )
window.getComputedStyle(oDiv1,null).attr //( W3C )
6 使用腳本添加樣式與瀏覽器的差異
當在連接外部樣式后,再在其后面使用JavaScript 腳本插入內部樣式時(即內部樣式使用腳本創建),
<html><head>
<title> demo </title>
<link rel="stylesheet" href="styles.css" type="text/css" /> // <!-- 添加外部CSS 樣式 -->
<!-- 在外部的styles.css文件中,代碼如下:
h3 {color:blue;}
-->
<script type="text/javascript"> // <!-- 使用javascript 創建內部CSS 樣式 -->
<!--
(function(){
var agent = window.navigator.userAgent.toLowerCase();
var is_op = (agent.indexOf("opera") != -1);
var is_ie = (agent.indexOf("msie") != -1) && document.all && !is_op;
var is_ch = (agent.indexOf("chrome") != -1);
var cssStr="h3 {color:green;}"; //樣式
var s=document.createElement("style"); //新建<stylr>元素
var head=document.getElementsByTagName("head").item(0); //取Head元素
var link=document.getElementsByTagName("link"); //取Link
link=link.item(0);
if (is_ie){
if (link) head.insertBefore(s,link);
else head.appendChild(s);
document.styleSheets.item(document.styleSheets.length-1).cssText=cssStr; //最后一個Style所有內容
}
else if(is_ch){
var tn=document.createTextNode();
tn.nodeValue=cssStr;
s.appendChild(tn); //在IE中非法
head.insertBefore(s,link);
}
else {
s.innerHTML=cssStr; //在IE中非法
head.insertBefore(s,link);
}
})();
//-->
</script>
</head> <body>
<h3>在IE中我是綠色,非IE瀏覽器下我是藍色!</h3>
</body></html>
結果:在Firefox / Chrome / Safari / Opera 中,文字都是藍色的。而在IE 瀏覽器中,文字卻是綠色的。