DIV CSS 佈局教程網

style、currentStyle、runtimeStyle 三者到底差在哪
編輯:關於JavaScript     

這三個屬性名字很像,職責卻完全不同,搞混就會出現「明明設了樣式卻讀不到」的狀況。

style:只看得到行內樣式

obj.style 只能取得寫在標籤上的 inline style,讀不到外部 CSS 檔,也讀不到 <head> 裡 <style> 宣告的規則。所以當你寫 obj.style = "color:red" 時之所以有效果,其實只是在該標籤上多加了一個 style 屬性,靠優先級把它疊上去而已。

currentStyle:讀取最終生效的樣式

IE 的 currentStyle 強得多,它能拿到該節點所有來源的樣式,而且會依照優先級回傳「畫面上真正呈現的那一個」。

<html>
<head>
<style>
.lala{ color:yellow; }
</style>
</head>
<body>
<div id="tt" style="color:blue;" class="lala">1111</div>
</body>
<script>
alert(document.getElementById("tt").currentStyle.color); // blue
</script>
</html>

行內樣式優先於 class,所以 currentStyle.color 是 blue。若把 div 的行內 style 拿掉,改成 <div id="tt" class="lala">,currentStyle.color 就變成 yellow,而此時 style.color 是空的。

runtimeStyle:最高優先級的臨時樣式

runtimeStyle 可以對節點賦值,且它的優先級最高,壓過行內樣式。

<script>
document.getElementById("tt").runtimeStyle.color = "black";
alert(document.getElementById("tt").currentStyle.color); // black
alert(document.getElementById("tt").runtimeStyle.color); // black
alert(document.getElementById("tt").style.color);        // blue
</script>

畫面實際顯示黑色,但只有 currentStyle 與 runtimeStyle 讀得到這個值,style.color 依然是標籤上原本寫的 blue。這三個都是 IE 特有(runtimeStyle 尤其冷門),跨瀏覽器開發時對應的做法是 getComputedStyle()。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved