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