文章出處

前面的話

  在實際工作中,我們使用javascript操作CSS樣式時,如果要改變大量樣式,會使用腳本化CSS類的技術,本文將詳細介紹腳本化CSS類

 

style

  我們在改變元素的少部分樣式時,一般會直接改變其行間樣式

<div id="test" style="height:100px;width:100px;background-color:blue;"></div>
<script>
test.onclick = function(){
    test.style.backgroundColor = 'green';
}
</script>

cssText

  改變元素的較多樣式時,可以使用cssText

<div id="test" style="height:100px;width:100px;background-color:blue;"></div>
<script>
test.onclick = function(){
    test.style.cssText = 'height:50px;width:50px;background-color:green';
}
</script>

css類

  更常用的是使用css類,將更改前和更改后的樣式提前設置為類名。只要更改其類名即可

<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(){
    test.className = 'small';
}
</script>

classList

  如果要改變多個類名,使用classList更為方便

  [注意]IE9-瀏覽器不支持

<style>
.big{
    height:100px;
    width:100px;
}
.small{
    height:50px;
    width:50px;
}    
.green{
    background-color:green;
}
.blue{
    background-color:blue;
}
</style>
<div id="test" class="big green"></div>
<button id="btn1">大小變化</button>
<button id="btn2">顏色變化</button>
<script>
btn1.onclick = function(){
    test.classList.toggle('small');
}
btn2.onclick = function(){
    test.classList.toggle('blue');
}
</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.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>

  在1萬次循環中,改變style屬性中的具體樣式花費了59.937ms,改變style屬性中的cssText花費了38.065ms,而改變css類名只花費了9.534ms

  由此可見,使用腳本化CSS類的方式可以大大地提高性能

 

最后

  腳本化CSS的場景非常常見,一直提倡使用腳本化CSS類的方式來操作CSS,以為只是為了方便。感覺腳本化CSS類應該和使用cssText的性能差不多,但沒想到最終結果竟然不是同一個數量級的,改變CSS類名的性能竟然提升這么多

  少一點感性認識,多一些理性測試

  歡迎交流


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()