一种方法是将要删除的 div 替换为占位符,然后为占位符和原始内容设置动画。
使用这个片段:使用 jQuery 将一个元素定位在另一个元素之上
您的代码可以更改为这样的内容(我使用单击该项目在此处触发删除):
演示
CSS
div { box-sizing: border-box; }
.item, .placeholder {
float: left;
width: 100px;
height: 100px;
border: 1px solid black;
margin: 5px;
position: relative;
background: white;
-webkit-transition: all 1s ease;
}
.placeholder {
opacity: 0;
border: 0px;
}
.item.hide {
border: 1px solid rgba(0,0,0,0);
margin: 0px;
top: 500px;
opacity: 0;
overflow: hidden;
z-index: -1;
}
.placeholder.hide {
width: 0;
height: 0;
margin: 0;
border: 0;
}
脚本
$('.item').on('click', function(evt) {
var $this = $(this);
var $new = $($this.clone());
$new.addClass('placeholder');
$this.replaceWith($new);
$this.positionOn($new);
$this.appendTo($('body'));
setTimeout(function() {
$this.css({top: '', left: ''});
$this.addClass('hide');
$new.addClass('hide');
}, 0);
});
片段来自: 使用 jQuery 将一个元素定位在另一个元素上
// Reference: http://snippets.aktagon.com/snippets/310-positioning-an-element-over-another-element-with-jquery
$.fn.positionOn = function(element, align) {
return this.each(function() {
var target = $(this);
var position = element.position();
var x = position.left;
var y = position.top;
if(align == 'right') {
x -= (target.outerWidth() - element.outerWidth());
} else if(align == 'center') {
x -= target.outerWidth() / 2 - element.outerWidth() / 2;
}
target.css({
position: 'absolute',
zIndex: 5000,
top: y,
left: x
});
});
};
现在,当网格崩溃时,您的旧 div 会以动画方式消失。
如果您愿意在代码中添加另一个库,请查看Metafizzy 的 Masonry/Isotope。他们被设计来做这种事情。