JavaScript取得CSS樣式
語法:
? ??nodeObject.style.cssProperty
#其中,nodeObject 為節(jié)點(diǎn)對(duì)象,cssProperty 是CSS屬性。
例如:
document.getElementById("demo").style.height; document.getElementById("demo").style.border;
注意:對(duì)於由 “ - ” 分隔的CSS屬性,要去掉 “ - ” ,並將 “ - ” 後的第一個(gè)字母大寫。例如:
background-color 要寫?backgroundColor
line-height 要寫?lineHeight
例如:
document.getElementById("demo").style. backgroundColor; document.getElementById("demo").style.lineHeight;
舉例,取得id="demo" 的節(jié)點(diǎn)的樣式:
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;"> 點(diǎn)擊這里獲取CSS樣式 </div> <script type="text/javascript"> document.getElementById("demo").onclick=function(){ alert( "高度:"+this.style.height+"\n"+ "寬度:"+this.style.width+"\n"+ "上邊距:"+this.style.marginTop+"\n"+ "對(duì)齊:"+this.style.textAlign+"\n"+ "行高:"+this.style.lineHeight+"\n"+ "背景顏色:"+this.style.backgroundColor ); } </script>
對(duì)上述程式碼稍作修改,將CSS 樣式與HTML 分開:
<style> #demo{ height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc; } </style> <div id="demo"> 點(diǎn)擊這里獲取CSS樣式 </div> <script type="text/javascript"> document.getElementById("demo").onclick=function(){ alert( "高度:"+this.style.height+"\n"+ "寬度:"+this.style.width+"\n"+ "上邊距:"+this.style.marginTop+"\n"+ "對(duì)齊:"+this.style.textAlign+"\n"+ "行高:"+this.style.lineHeight+"\n"+ "背景顏色:"+this.style.backgroundColor ); } </script>
可以發(fā)現(xiàn),將CSS 樣式與HTML程式碼分開後無法取得CSS樣式。這是因?yàn)?br/>? ??nodeObject.style.cssProperty
取得的是DOM節(jié)點(diǎn)上style 屬性定義的樣式,如果不存在style 屬性,或是style 屬性沒有定義對(duì)應(yīng)的樣式,則是無法獲取的。
也就是說,JavaScript 不會(huì)到 <style> 標(biāo)籤或 CSS 檔案去取得對(duì)應(yīng)的樣式,只能取得 style 屬性定義的樣式。