完成动画后分离并移动元素

时间:2017-06-05 13:33:13

标签: javascript jquery css dom css-animations

我有一个项目列表,其中包含与每个项目关联的关闭按钮。单击时,播放动画,向上滑动列表并成功删除项目。

$(document).on("click", ".close-button", function(e) { //removes with animation
    $(this).parent().animate({
        opacity: 0
    }, 250, function() {
        $(this).animate({
                marginBottom: 0
            }, 250)
            .children()
            .animate({
                padding: 0
            }, 250)
            .wrapInner("<div />")
            .children()
            .slideUp(250, function() {
                $(this).closest(".element").remove();
            });
    });
});

我尝试修改上面的代码段,以便不分离项目,而是将项目分离并移动到另一个视图。我尝试使用下面的代码,无济于事。 $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)

摆脱动画会将元素成功移动到不同的视图。

$(document).on("click", ".close-button" ,function(e) { //detaches w/o animation
  $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)
});

我想保留动画当然,但我无法弄清楚如何分离而不是移除它们同时保持它们。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

当你动画时,父this指的是动画元素。结果,对关闭按钮的引用将丢失。

存储当前元素的元素的引用以及稍后用于目标。

$(document).on("click", ".close-button", function (e) { 
    //Store the reference
    var $this= $(this);
    $(this).parent().animate({
        opacity: 0
    }, 250, function () {
        $(this).animate({
            marginBottom: 0
        }, 250)
        .children()
        .animate({
            padding: 0
        }, 250)
        .wrapInner("<div />")
        .children()
        .slideUp(250, function () {
            $this.closest('.element').prependTo('#diff-view').hide().slideDown(250)
        });
    }); 
});