標籤:java har rbo iss window win 對象 樣式 main
1.操作對象的屬性
注意:
標籤屬性與DOM對象屬性的相應關係:
絕大部分2者是同樣的。如:imgobj.src屬性相應<img src="" >中src屬性,但也有例外,如<div class="main" >中,操作class屬性用divobj.className。
CSS屬性與DOM對象屬性的相應關係:
1. 兩者通過obj.style.css屬性名稱 相相應 如:obj.style.width。
2.假設CSS屬性帶有橫線,如border-top-style ,則把橫線去掉並將橫線後字母大寫 。 如:obj.style.borderTopStyle。
範例:
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html"; charset="utf-8"/><title></title></head><style type="text/css">.test1{background: red;}.test2{background: green;}</style><body><div class="test1" onclick="a();" style="width:200px; height:200px; border-bottom:1px solid">點擊div,使其背景色紅綠交替,寬高添加5px,下邊框增粗1px;</div><script type="text/javascript">function a(){var div = document.getElementsByTagName(‘div‘)[0];if(div.className.indexOf(‘test1‘)>=0){div.className = ‘test2‘;}else{div.className = ‘test1‘;}div.style.width = parseInt(div.style.width)+10+‘px‘;div.style.height = parseInt(div.style.height)+10+‘px‘;div.style.borderBottomWidth = parseInt(div.style.borderBottomWidth)+1+‘px‘;}</script></body></html>
擷取對象在記憶體中計算後的樣式:
用obj.currenStyle 和window.getComputedStyle()擷取。
注意:僅僅有IE和Opera支援使用currentStyle擷取HTML Element的計算後的樣式,其它瀏覽器不支援。標準的瀏覽器用getComputedStyle,IE9以上也支援getComputedStyle。
window.getComputedStyle(obj,虛擬元素);
參數說明:1.第一個參數為要擷取計算後的樣式的目標元素
2.第二個參數為期望的虛擬元素,如:‘:after’。‘:first-letter’等。一般設為 null。
function getStyle(obj,attr){ return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,null)[attr];} //考慮相容性,封裝函數。
上述範例改動後的版本號碼:改動後的版本號碼將 CSS 的style屬性放到了body之外。
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html"; charset="utf-8"/><title></title></head><style type="text/css">div{width: 200px;height: 200px;border-bottom: 1px solid black;}.test1{background: red;}.test2{background: green;}</style><body><div class="test1" onclick="a();" >點擊div,使其背景色紅綠交替,寬高添加5px,下邊框增粗1px;</div><script type="text/javascript">function getStyle(obj,attr){ return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,null)[attr];} //考慮相容性,封裝函數。
function a(){var div = document.getElementsByTagName(‘div‘)[0];if(div.className.indexOf(‘test1‘)>=0){div.className = ‘test2‘;}else{div.className = ‘test1‘;}//alert(getStyle(div,‘width‘));//return;div.style.width = parseInt(getStyle(div,‘width‘))+10+‘px‘;div.style.height = parseInt(getStyle(div,‘height‘))+10+‘px‘;div.style.borderBottomWidth = parseInt(getStyle(div,‘borderBottomWidth‘))+1+‘px‘;}</script></body></html>
JavaScript中操作對象的屬性