我已经编辑了你的 jsfiddle 来移动项目,就像它们是浮动的一样。它假设您的边距和宽度对于包装器中的每个 div 都是相同的,并且如果您的 css 发生变化,它将自动计算出间距的宽度和高度
var wrapper = $('#wrapper'),
items = wrapper.children('div'),
len = items.length,
itemWidth = items.innerWidth() + parseInt(items.css('margin-left')) + parseInt(items.css('margin-right')),
itemHeight = items.innerHeight() + parseInt(items.css('margin-top')) + parseInt(items.css('margin-bottom'));
items.css('float', 'none');
function absPos() {
var cols = Math.floor(wrapper.width() / itemWidth);
items.each(function() {
var left = ($(this).index() % cols) * itemWidth; //the bit in brackets calculates which column the div should be in (the remainder of the current index of your item divided by the number of columns per row), then you times that by item width as worked out above, you use the index as this will allow you to start at left:0
var height = Math.floor($(this).index() / cols) * itemHeight //the bit in brackets calculates which row the div should be in, then you times that by item height as worked out above, you use the Math.floor as this will allow you to start at top:0. Should have really called this top!
$(this).css({
'position' : 'absolute',
'top': height,
'left': left
});
});
wrapper.height((Math.ceil(len / cols)) * itemHeight);
}
$(window).resize(function() {
absPos();
});
absPos();
http://jsfiddle.net/Fgcqs/12/