1. 程式人生 > >DOM獲取樣式的值

DOM獲取樣式的值

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #box{
                width: 200px;
                height: 200px;
                background-color:green;
            }
        </style>
</head> <body> <button id="btn1">紅色</button> <button id="btn2">綠色</button> <button id="btn3">切換</button> <div id="box"></div> <script> var o=document.getElementById('box'); var
btn1=document.getElementById('btn1'); var btn2=document.getElementById('btn2'); var btn3=document.getElementById('btn3'); //變紅 btn1.onclick=function(){ o.style.background='red'; } //變藍 btn2.onclick=function
(){
o.style.background='green'; } //兩種顏色切換 btn3.onclick=function(){ //獲取物件o的樣式 返回值是樣式物件 var sty=window.getComputedStyle(o,null); //sty.屬性名 獲取樣式的值 var col=sty.backgroundColor; console.log(col);//控制檯列印獲取的背景色 if(col=='rgb(0, 128, 0)'){ o.style.background='red'; }else{ o.style.background='green'; } }
</script> </body> </html>

獲取樣式的值:
style既是屬性 也是物件
(1)node.style.樣式名; 此方法只能取到行間樣式
(2)var sty=window.getComputedStyle(物件,null);獲取目標物件的樣式 ;
返回值是樣式物件 sty.屬性名;
既能獲取行間樣式屬性值 又能獲取樣式表屬性的值;