作业帮 > CSS > 教育资讯

css教程:巧用cssText属性批量操作样式

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/09 14:30:40 CSS
css教程:巧用cssText属性批量操作样式CSS
【无忧考网-css教程:巧用cssText属性批量操作样式】:

给一个HTML元素设置css属性,如

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

这样写太罗嗦了,为了简单些写个工具函数,如

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

发现 Google API 中使用了cssText属性,后在各浏览器中测试都通过了。一行代码即可,实在很妙。如

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

和innerHTML一样,cssText很快捷且所有浏览器都支持。此外当批量操作样式时,cssText只需一次reflow,提高了页面渲染性能。

但cssText也有个缺点,会覆盖之前的样式。如

1<div style="color:red;">TESTdiv>

想给该div在添加个css属性width

1div.style.cssText = "width:200px;";

这时虽然width应用上了,但之前的color被覆盖丢失了。因此使用cssText时应该采用叠加的方式以保留原有的样式。

1function setStyle(el, strCss){
2    var sty = el.style;
3    sty.cssText = sty.cssText + strCss;
4}

使用该方法在IE9/Firefox/Safari/Chrome/Opera中没什么问题,但由于 IE6/7/8中cssText返回值少了分号 会让你失望。

因此对IE6/7/8还需单独处理下,如果cssText返回值没";"则补上

01function setStyle(el, strCss){
02    function endsWith(str, suffix) {
03        var l = str.length - suffix.length;
04        return l >= 0 && str.indexOf(suffix, l) == l;
05    }
06    var sty = el.style,
07        cssText = sty.cssText;
08    if(!endsWith(cssText, ';')){
09        cssText += ';';
10    }
11    sty.cssText = cssText + strCss;
12}
CSS