JQuery动画和效果适用于$ .when()和then()的几个元素

问题描述 投票:0回答:1

我有像这样的html元素,

<div class="row h-100 p-3 justify-content-center align-items-center m-0">
        <h1 class="col-12 text-center position-absolute welcome-line-1 d-none-edited" id="welcome-line-1">TEXT 01</h1>
        <h3 class="col-12 text-center position-absolute welcome-line-2 d-none-edited" id="welcome-line-2">TEXT 02</h3>
        <h2 class="col-12 text-center position-absolute welcome-line-3 d-none-edited" id="welcome-line-3">TEXT 03</h2>
    </div>

我想使用jQuery为这些文本元素设置动画。这是我的一个元素的jquery代码。

var line_1_anim = function(){
            return $('#welcome-line-1')
                .css('opacity', 0)
                .slideDown('slow')
                .animate(
                    { opacity: 1 },
                    { queue: false, duration: 'slow' }
                )
                .delay(1000)
                .slideUp('slow');
        }

并假设我有三个元素,我使用这种方法使用$ .when()然后()逐个动画每个元素

$.when(line_1_anim())
   .then(line_2_anim)

我试图降低代码复杂性并实现这一目标。我的功能已经运作,但我想做更多。因为如果我想再添加10个元素,我必须重复10次相同的代码。所以我写了这样的东西。

var line_animation = function(selector,delay){
            return selector
                .css('opacity', 0)
                .slideDown('slow')
                .animate(
                    { opacity: 1 },
                    { queue: false, duration: 'slow' }
                )
                .delay(delay)
                .slideUp('slow');
        }

        $.when(line_animation(line_1,1000))
        .then(line_animation(line_2,2000))
        .then(line_animation(line_3,3000));

我只是计划改变选择器和延迟并多次运行相同的方法。但这并不像我想的那样有效。所有功能一次完成,而不是一个接一个地工作。

知道我的方法有什么问题,我怎么能实现这个目标。

希望我已经解释了我的问题,一切都很清楚。

javascript jquery performance jquery-animate code-complexity
1个回答
1
投票

jQuery promise example你可以重写所有(例如:line_animation应该返回一个promise而不是一个jQuery对象):

var line_animation = function (selector, delay) {
    var dfd = jQuery.Deferred();
    selector.css('opacity', 0)
            .slideDown('slow')
            .animate({opacity: 1}, {queue: false, duration: 'slow'})
            .delay(delay)
            .slideUp('slow', function () {
                dfd.resolve("hurray");
            });
    return dfd.promise();  // return a promise....
}

$.when(line_animation($('#welcome-line-1'), 1000)).then(function () {
    line_animation($('#welcome-line-2'), 2000).then(function () {
        line_animation($('#welcome-line-3'), 3000);
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="row h-100 p-3 justify-content-center align-items-center m-0">
    <h1 class="col-12 text-center position-absolute welcome-line-1 d-none-edited" id="welcome-line-1">TEXT 01</h1>

    <h3 class="col-12 text-center position-absolute welcome-line-2 d-none-edited" id="welcome-line-2">TEXT 02</h3>

    <h2 class="col-12 text-center position-absolute welcome-line-3 d-none-edited" id="welcome-line-3">TEXT 03</h2>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.