给一个html元素设置css属性,传统做法:
var mybox= document.getElementById("mybox");
mybox.style.width = "200px";
mybox.style.height = "70px";
mybox.style.display = "block";
mybox.style.width = "200px";
mybox.style.height = "70px";
mybox.style.display = "block";
这样写很烦,尤其是很多的时候,一个样式一行,天啊!
工具函数 :
function setStyle(obj,css){
for(var atr in css)
obj.style[atr] = css[atr];
}
var mybox = document.getElementById("mybox");
setStyle(mybox,{"200px",height:"70px",display:"block"})
for(var atr in css)
obj.style[atr] = css[atr];
}
var mybox = document.getElementById("mybox");
setStyle(mybox,{"200px",height:"70px",display:"block"})
使用cssText属性,想怎么写就怎么写:
var mybox = document.getElementById("mybox");
mybox.style.cssText="200px;height:70px;display:bolck";
mybox.style.cssText="200px;height:70px;display:bolck";
跟书写CSS一样,还可以支持属性值缩写border:#000 solid 1px;
测试浏览器版本如下(与浏览器模式无关):
IE 6/7
IE 8 (Emulate IE7)
IE 8 (Enforce IE8)
Opera 10.10
Firefox 3.5.6
Safari 4.0.3
Chrome 4.0.266.0
Safari 4.0.3
Chrome 4.0.266.0