改变元素的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);