<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> *{text-align: center} input{margin-top:30px;padding:10px;} #div1{width:500px;height:300px;background:red;margin:10px auto;} </style></head><body><input type="button" value="style" id="btn"><div id="div1"></div><script> //获取非行间样式 function getStyle(obj,attr){ //获取非行间样式,obj是对象,attr是值 if(obj.currentStyle){ //针对ie 获取非行间样式 return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; //针对非ie } } //为对象写入/获取css样式 function css(obj,attr,value){ //对象,样式,值。传2个参数为获取样式,3个是设置样式 if(arguments.length==2){ return getStyle(obj,attr); }else{ if(arguments.length==3){ obj.style[attr]=value; } } } window.onload=function(){ var oDiv=document.getElementById("div1"); var oBtn=document.getElementById("btn"); oBtn.onclick=function(){ alert(getStyle(oDiv,"height")); css(oDiv,"background","green"); alert(css(oDiv,"width")); } } </script></body></html>
时间: 2024-12-27 09:06:45