亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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 屬性沒有定義相應(yīng)的樣式,則是無法獲取的。

也就是說,JavaScript 不會(huì)到 <style> 標(biāo)簽或者 CSS 文件去獲取相應(yīng)的樣式,只能獲取 style 屬性定義的樣式。

繼續(xù)學(xué)習(xí)
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標(biāo)題文檔</title> <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> </head> <body> </body> </html>
提交重置代碼