2017-01-16 47 views
0

嘗試在頁面上按下複選框時重置css動畫。它適用於單個div,但我想讓它在同一時間適用於所有div,所以我使用了for。問題只是最後的div復位。我究竟做錯了什麼?任何幫助讚賞。在陣列上重置CSS動畫

<div class="total">Subtotal: $300</div> 
<div class="total">Subtotal: $300</div> 
<div class="total">Subtotal: $300</div> 
    <div class="produse"> 
    <input type="checkbox" name="product" value="Logo design">I have a bike 
    <br><input type="checkbox" name="product" value="Website layout">I have a car 
</div> 

jQuery(document).ready(function($){ 
$(":checkbox").on("click", function(){ 
    // restart animation 
    var totalcl = document.getElementsByClassName("total"); 
    var tlength = document.getElementsByClassName("total").length; 
    for (i=0; i<tlength; i++){ 
    totalcl = document.getElementsByClassName("total")[i]; 
    totalcl.style.webkitAnimation = 'none'; 
    setTimeout(function() { 
     totalcl.style.webkitAnimation = ''; 
    }, 10); 
    } 
}); 
}); 

PS。我知道我應該使用getElementById,但它不是一個選項,因爲它是一個wordpress插件,複選框沒有id標籤。

+0

典型問題,請在此頁面中檢查:「在循環中創建閉包:常見錯誤」:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures此處也沒有多少解決方法。因爲。 – sinisake

+0

因爲你正在使用jQuery你可能想要利用.each()http://api.jquery.com/jquery.each/ –

回答

1

既然你已經使用jQuery,你應該使用它的最大瀏覽器兼容的方法:

jQuery(document).ready(function($){ 
    $(":checkbox").on("click", function(){ 
     // restart animation 
     $(".total") 
      .css({ 
       fontSize: "" 
      }) 
      .animate({ fontSize: "24px" }, 1000); 
    }); 
}); 

See JSFiddle Demo

有關如何使用動畫來獲得你想要的效果的詳細信息,請參閱jQuery Documentation

+0

當然......感謝隊友! –