DOMCSS

改变元素的CSS样式的三种方式性能比较

<div id="test" style="height:100px;width:100px;background-color:blue;"></div>
<script>
test.onclick = function(){
    console.time();
    for(var i = 0; i < 10000; i++){
        test.style.backgroundColor = 'green';
        test.style.height = '50px';    
        test.style.width = '50px';        
    }
    console.timeEnd();//59.937ms
}
</script>
/*****************************/
<div id="test" style="height:100px;width:100px;background-color:blue;"></div>
<script>
test.onclick = function(){
    console.time();
    for(var i = 0; i < 10000; i++){
    test.style.cssText = 'height:50px;width:50px;background-color:green';
    }
    console.timeEnd();//38.065ms
}
</script>
/*****************************/
<style>
.big{
    height:100px;
    width:100px;
    background-color:blue;
}
.small{
    height:50px;
    width:50px;
    background-color:green;
}    
</style>
<div id="test" class="big"></div>
<script>
test.onclick = function(){
    console.time();
    for(var i = 0; i < 10000; i++){
    test.className = 'small';
    }
    console.timeEnd();//9.534ms
}
</script>

提倡使用脚本化CSS类的方式来操作CSS。

动态CSS

// 外置添加CSS
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
var head = document.getElementsByTagName('head')[0];
head.appendChild(link)
// 内置添加CSS
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML = ".box{height:100px;width:100px;background-color: pink;}";
var head = document.getElementsByTagName('head')[0];
head.appendChild(style);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,806评论 1 92
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,741评论 1 45
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,315评论 0 3
  • 端午节的正确打开方式:吃凉糕,插艾草,系五色索,挂香包。 亲手做每一样东西,让每一根丝线都充满感情,这就是仪式感。...
    王小唐阅读 245评论 0 1
  • 图文:玉琼 主播:玉琼 晚安曲:菩提偈 序 来到微笑佛国,怎能不去看庙? 南朝四百八十寺,多少楼台烟雨中。此诗本...
    玉琼千里目阅读 621评论 11 15