JQuery:对 .appended元素的高度进行动画处理

JQuery: Animate the height of an .appended element

本文关键字:动画 处理 高度 appended 元素 JQuery      更新时间:2023-09-26

我在单击时附加多个div,我需要包含元素慢慢增加高度以容纳新附加的div,而不是立即跳到新高度。我一直在拖网堆栈溢出和网络,但似乎找不到答案;至少不是我可以用我在jquery中有限的知识实现的。

我认为最好的方法是在 .fadein 之前将附加的div 的高度从 0px 动画化到 40px(或任何高度)??

$("#Addrow1").click(function () {
    var agi = 1;
    $('.item').each(function () {
        agi++;
    });
    $("#livingX").append('<div class="something"><input class="item" placeholder="Item Name" name="LIVFUR' + agi + '" type="text" style="width:200px;"/></div>').children(':last').hide().fadeIn(500);
    return false; 
});

这是 JSFiddle

当您单击按钮时,新元素会很好地附加一个淡入,但按钮(以及实际实现中的容器)都跳到它们的新位置/高度。我该如何解决这个问题?

任何帮助将不胜感激。

尝试.find('.add-container:last').hide().slideDown(500)而不是.children(':last').hide().fadeIn(500)

$("#Addrow1").click(function () {
    var agi = 1;
    $('.item').each(function () {
        agi++;
    });
    $("#livingX").append('<div class="add-container"><input class="item" placeholder="Item Name" name="LIVFUR' + agi + '" type="text" style="width:200px;"/></div>').find('.add-container:last').hide().slideDown(500);
    return false;
});

js小提琴示例

或者在滑动时隐藏,然后淡入(如下面评论中的小提琴所示)使用:

$("#livingX").append('<div class="add-container"><input class="item" placeholder="Item Name" name="LIVFUR' + agi + '" type="text" style="width:200px;"/></div>').find('.add-container:last').hide().css('opacity', 0).slideDown(500, function () {
    $(this).fadeTo('slow',1);
});
您需要

在附加新内容之前和之后获取高度。将高度设置为之前的高度,然后将其动画化为生成的高度:

$("#Addrow1").click(function () {
    var agi = 1;
    $('.item').each(function () {
        agi++;
    });
    // height before added content
    var heightBefore = $('#livingX').height();
    // append the content and remove inline-styling 
    $("#livingX").append('<div class="add-container"><input class="item" placeholder="Item Name" name="LIVFUR' + agi + '" type="text" style="width:200px;"/></div>').removeAttr('style');
    // height after added content
    var heightAfter = $('#livingX').height();
    // set the height to the original height, then animate it to the new height
    $('#livingX').css('height',heightBefore).animate({height: heightAfter}, 500);
    return false;
});

小提琴