JavaScript取得CSS樣式
語法:
nodeObject.style.cssProperty
#其中,nodeObject 為節點對象,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" 的節點的樣式:
<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>可以發現,將CSS 樣式與HTML程式碼分開後無法取得CSS樣式。這是因為
nodeObject.style.cssProperty
取得的是DOM節點上style 屬性定義的樣式,如果不存在style 屬性,或是style 屬性沒有定義對應的樣式,則是無法獲取的。
也就是說,JavaScript 不會到 <style> 標籤或 CSS 檔案去取得對應的樣式,只能取得 style 屬性定義的樣式。
新建檔案
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<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>
</head>
<body>
</body>
</html>
預覽
Clear
- 課程推薦
- 課件下載
課件暫不提供下載,工作人員正在整理中,後期請多關注該課程~ 















