js设置css样式.

时间:2023-03-08 15:44:57
js设置css样式.

在js设置css样式做法

var obj = document.getElementById('div');
obj.style.width = '100px';
obj.style.height = '100px';

但是上面的写法如果样式多了就会造成写了一堆的js于是有了封装函数的写法

var obj = document.getElementById('div');
function setStyle(obj, css) {
for(var attr in obj){
obj.style[attr] = css[attr];
}
}
setStyle(obj,{width:"100px",height:"100px"});

更简单的写法

var obj = document.getElementById('div');
obj.style.cssText = "width:100px; height:100px;";