我目前正在开发一个具有动态添加和删除文件输入框的接口。使用jQuery,我已经能够为容纳所有"文件输入"框的容器元素的视觉外观设置动画,并在添加空间后淡入正在添加的元素。
让我困惑的是,如果一个"文件输入"框从堆栈的中间移除,那么它之后的其他框在移除后会卡入到位。
我想知道的是,是否有人有经验如何在移除中间元素后为现有元素设置动画。
近似HTML:
<div class="fileFields">
<!-- first example field group -->
<div class="fileField">
<span class="buttonBrowse"></span>
<span class="fileName"></span>
<span class="hiddenInput"><input name="file_0" type="file" /></span>
<span class="buttonRemove"></span>
</div>
<!-- middle example field group -->
<div class="fileField">
<span class="buttonBrowse"></span>
<span class="fileName"></span>
<span class="hiddenInput"><input name="file_1" type="file" /></span>
<span class="buttonRemove"></span>
</div>
<!-- last example field group -->
<div class="fileField">
<span class="buttonBrowse"></span>
<span class="fileName"></span>
<span class="hiddenInput"><input name="file_1" type="file" /></span>
<span class="buttonRemove"></span>
</div>
</div>
<div class="fileFieldControls">
<span class="buttonAdd"></span>
</div>
因此,为了清晰起见,如果您查看HTML示例的内联注释,我希望从正确答案中得到的是删除"中间示例字段组"的方法,并动画化"最后一个示例字段组"和它后面的任何其他字段组的重新定位。
编辑:jQuery代码包含
function buttonAddClick() {
// Container...
fileField = $('<div class="fileField"></div>');
// Interior elements...
fileField.append('<span class="buttonBrowse">'+svgButtons['browse']+'</span>');
fileField.append('<span class="fileName"></span>');
fileField.append('<span class="hiddenInput"><input name="" type="file" /></span>');
fileField.append('<span class="buttonRemove">Remove</span>');
// Actions...
fileField.children('.buttonBrowse').on('click', function() {
$(this).siblings('.hiddenInput').find('input[type=file]').trigger('click');
});
fileField.children('.hiddenInput').find('input[type=file]').on('change', function() {
$(this).parent().siblings('.fileName').html($(this).val().split('\').pop());
});
fileField.children('.buttonRemove').on('click', function() {
$(this).parent().fadeOut(500, function() {
// This is where the question answer will likely go...
$(this).remove();
$('.fileFields').animate( { "height" : $('.fileFields').outerHeight() - 37 }, 500);
});
});
// Animate the field adding...
$('#groupFiles').animate( { "height" : $('#groupFiles').outerHeight() + 37 }, 500, function() {
fileField.appendTo('.fileFields').hide().fadeIn(500);
} );
}
// Add Button Actions...
$('.buttonAdd').on('click', buttonAddClick);
$('.buttonAdd').trigger('click');
您可以将可见性设置为hidden
,使元素不可见,同时仍占用空间。然后将高度设置为0,并在完成时进行回调,从DOM中删除元素。
在下面的示例中,我隐藏了中间的fileField
,因为这正是您所询问的,但更新它以使其适用于任何fileField并不困难。
$('#remove').on('click', function () {
$('.fileField').eq(1).css('visibility', 'hidden').animate({
height: 0
}, 300, function () {
$(this).remove();
});
});
工作演示