js怎样获取非行间样式,设置行间样式?

xiaoxiao2021-02-28  48

JavaScript的style属性可以获取html上标签的样式,但是不可以获取css里的样式我们怎么才能获取css里的样式?这时候就要用到JavaScript提供的currentStyle(ie)和getComputedStyle(火狐)来获取了!

<!DOCTYPE html> <html> <head> <meta charset="gbk"> <title>获取行间样式</title> <style> #box{width: 200px;height: 200px;background: red;} </style> </head> <body> <div id="box"></div> <script> window.onload=function(){ var oBox=document.getElementById('box'); //获取行间样式 function getStyle(obj,attr) { if(obj.currentStyle){ //针对ie获取非行间样式 return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr];//针对谷歌,火狐获取非行间样式 } } //获取行间样式或者设置行间样式 function css(obj,name,value){ if(arguments.length==2){ //arguments参数数组,当参数为2时表示获取行间样式 return getStyle(obj,name); }else{ if(arguments.length==3){ //arguments参数数组,当参数为3时表示设置样式 return obj.style[name]=value; } } } alert(getStyle(oBox,'width')); css(oBox,'background',"blue"); alert(css(oBox,'background')); } </script> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-75075.html

最新回复(0)