Jquery 为 add/removeClass 和 clone/remove 元素添加动画

Jquery add animation to add/removeClass and clone/remove elements

我想为 add/removeClass 和 clone/remove 元素添加动画(可能相同)。对于 add/removeClass 函数,我尝试使用 bootstrap class "fade in" (没有成功)。对于 clone/remove 元素,我尝试使用 hide/show (仅成功删除)

HTML

<!-- CLONE BTN -->
<div class="row cust-gutters">
    <div class="col-md-12">
        <span id="cloneRow" class="label label-primary pointer">
            Add <span class="glyphicon glyphicon-plus"></span>
        </span>
    </div>
</div>

<div class="clonable-row-label hide fade">
    <div class="row">
        <div class="col-md-4">
            <label class="control-label" for="phone">Phone</label>
        </div>
    </div>
</div>
<div class="clonable-row hide fade">
    <div class="row">
        <div class="col-md-4">
            <div class="input-group">
                <input type="text" class="form-control input-sm" name="phone[]" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-trash deleteRow" aria-hidden="true"></span>
                </span>
            </div>
        </div>
    </div>
</div>

JS

$("#cloneRow").on('click', function() {
    var num = $(".clonable-row").length;
    if($(".clonable-row:first").hasClass("hide")) {
        $(".clonable-row:first, .clonable-row-label").addClass("in");
        $(".clonable-row:first, .clonable-row-label").removeClass("hide");
    } else {
        if(num < 4) {
            //var row = $('.clonable-row:first').clone(true);
            //row.insertAfter('.clonable-row:last').show().fadeIn(600);
            $(".clonable-row:first").clone(true).insertAfter(".clonable-row:last");
        }
    }
});

$(".deleteRow").on('click', function() {
    var num = $(".clonable-row").length;
    if(num == 1) {
        $('.clonable-row-label').addClass("hide").removeClass("in");
        $(this).closest('.clonable-row').addClass("hide").removeClass("in");
    } else {
        $(this).closest('.clonable-row').hide(600, function() {
            $(this).closest('.clonable-row').remove();
        });
    }
});

我该怎么做? 谢谢

JSFIDDLE

你应该使用:

$(".clonable-row:first").clone(true).insertAfter(".clonable-row:last").hide().fadeIn(600);

jQuery UI 提供 .addClass() and removeClass().

的动画版本

至于显示元素时的动画,您应该像现在一样使用 fadeIn()。请注意 fadeIn() 已经显示() 这样的元素,所以做类似 $(element).show().fadeIn() 的事情是没有意义的,因为当 fadeIn() 开始时,该元素将已经显示,并且 $(element ).fadeIn().show() 也是毫无意义的,因为 fadeIn() 在完成时已经完全显示了元素。

以下片段的问题是概念性的:

$(this).closest('.clonable-row').hide(600, function() {
    $(this).closest('.clonable-row').remove();
});

应该这样走:

$(this).closest('.clonable-row').hide(600, function() {
    // Note here that $(this) is already the element (jQuery-wrapped) you called .hide() on
    $(this).remove();
});

编辑

对于您的特定情况,插入克隆的元素,您应该在将其插入到 HTML 之前隐藏它:

$(".clonable-row:first").clone(true).hide().insertAfter(".clonable-row:last").fadeIn();