DOM获取样式的值

xiaoxiao2021-03-01  15

<!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.属性名; 既能获取行间样式属性值 又能获取样式表属性的值;

转载请注明原文地址: https://www.6miu.com/read-3450360.html

最新回复(0)