【问题标题】:Trying to animate the color of the boxes using JQuery尝试使用 JQuery 为框的颜色设置动画
【发布时间】:2019-06-16 21:01:18
【问题描述】:

我有 4 个带有某种颜色的框,我正在尝试通过一个接一个地更改它们的颜色来为它们设置动画。动画后的框应该恢复其原始颜色,然后下一个框应该动画。

正在使用的代码:

$(function(){

$(".button").click(function(){

for (var a = [1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];

$( ".rectangle"+random.toString() ).animate({
          backgroundColor: "#aa0000",
          color: "#fff",
        },2000,function(){$(this).removeAttr('style');} );

}
});

});

这会随机设置盒子的动画,但只有在所有盒子都被动画化后它们才会恢复到原始状态,但我希望每个盒子都设置动画,回到原始状态然后为下一个盒子设置动画。

【问题讨论】:

  • 能否也包含示例 HTML?

标签: javascript jquery animation jquery-animate css-animations


【解决方案1】:

我使用异步的方法,等待

$(function(){
        var a = [1, 2, 3, 4]

        async function loopTheBoxes ( arr, callback ) {
            for ( let i = 0; i < arr.length; i++ ) {
                await callback( arr[i] );
            }
        }

        function animateTheBoxes() {
            $(".button").click( () => {
                loopTheBoxes( a, ( index ) => {
                    return new Promise( ( resolve ) => {
                        $( ".rectangle-" + index ).animate({
                            backgroundColor: "#aa0000",
                            color: "#fff"
                          }, 2000, function() {
                              $(this).removeAttr( 'style' );
                              return resolve();
                          } );
                    });
                });
            });
        }

        animateTheBoxes();
});

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多