0

edit just to clarify what I want: my current algorithm is a little basic and makes too many rows. I want to use as little rows as possible without adding widows.

I am trying to layout my products without having one or two widows in the bottom row. I made a small prototype but it doesn't always work like expected (it should always try to use the maximum width while reducing the chance of having only 1 or 2 squares on the bottom row). jsfiddle.net/ffuUD

function format(val) {
    var decimal = val.toString().substr(val.toString().indexOf(".") + 1, 1)
    if ((val <= 4 || (decimal >= 6 || isInt(val))) && $('.product').outerWidth(true) * val < $('body').width() ) {
        return true;
    } else {
        return false;
    }
}
function recalculate() {
    for (var i = 1; i < 6; i++) {
        if (format($('.product').length/i)) {
            $('.products').width($('.product').outerWidth(true) * $('.product').length/i);
            break;
        }
    }
}

There should be a way to reduce widows and layout the divs in the most optimal way possible. Any tips?

expected results (try expanding the width of the jsfiddle window):

7 has a widow when the window isn't very large. the 3 rows should be 2.

11,14,17,20 should be in 3 rows instead of 4

13 is a hard one too but not exactly sure.

Update: If anyone knows a better way please answer: jsfiddle.net/ffuUD/3

4

1 回答 1

0

这是我能做的最好的:

jsfiddle.net/ffuUD/3

我刚刚添加Math.ceil()和删除了一些不需要的检查。

它有效,但可能有更清洁的方法来实现相同的结果。

于 2013-08-27T15:48:41.027 回答