我已经发布了使用的理想算法。仍然可以进行一些粗略的计算以使容器看起来整洁。
JS代码
var $container1 = $('#container1');
var $container2 = $('#container2');
$('.box').each(function(){
$(this).height(100 * Math.random());
});
var move = $container1.outerWidth();
$container2.css("margin-left",move + 10);
// Let us try to minimize the height difference
var h1 = $container1.height();
var h2 = $container2.height();
var diff = 20;
var currentDiff = h1-h2;
if (currentDiff > diff) {
alert('1 is bigger than 2');
reArrange($container1, $container2, Math.abs(currentDiff), diff);
}
if (currentDiff < -diff) {
alert('2nd is bigger than 1st');
reArrange($container2, $container1, Math.abs(currentDiff), diff);
}
// Logic: Send the minium height box to smaller container
function reArrange(largeC, smallC, currentDiff, diff) {
var minHeightBox = null;
var minH = 10000000000;
$('.box', largeC).each(function(){
if ($(this).height() < minH)
minHeightBox = this;
minH = $(this).height();
});
// If transfering this to other reduces the difference, transfer this otherwise returh false
if (minHeightBox !== null) {
var newDiff = (largeC.height() - minH) - (smallC.height() + minH);
newDiff = Math.abs(newDiff);
console.log(newDiff);
if (newDiff < currentDiff) {
smallC.append(minHeightBox);
currentDiff = largeC.height() - smallC.height();
//Recursively call the method
if (currentDiff > diff)
reArrange(largeC, smallC, currentDiff, diff);
}
}
}