首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js批量设立style属性

2012-10-20 
js批量设置style属性JS中给一个html元素设置css属性,可以通过style属性来操作var head document.getEleme

js批量设置style属性
JS中给一个html元素设置css属性,可以通过style属性来操作

    var head= document.getElementById("head");head.style.width = "200px";head.style.height = "70px";head.style.display = "block";


如果要设置的样式很多,这样写太罗嗦了,而且会造成浏览器渲染的reflow,懒人总是用懒办法,不是说程序员要越懒越好嘛,还有就是 懒人推动了科技的发展

    function setStyle(obj,css){    for(var atr in css)    obj.style[atr] = css[atr];}var head= document.getElementById("head");setStyle(head,{width:"200px",height:"70px",display:"block"})        


Firefox中还可以通过setAttribute来设置style样式

    dom.setAttribute("style","width:10px;height:10px;border:solid 1px red;")


一不小心造了个轮子,原来javaScript中有个现成的cssText属性,兼容各个浏览器,语法为:obj.style.cssText="样式";

        var head= document.getElementById("head");head.style.cssText="width:200px;height:70px;display:bolck";


通过js的cssText来批量修改样式目的是尽量避免页面reflow,提高性能

热点排行