使用jquery根据列的累积宽度将列分为组(行)

时间:2011-12-16 00:12:32

标签: javascript jquery

我生成了许多列(具有不同的宽度),我需要根据它们的宽度将它们分成组或行。每次列的累积宽度达到100%时,我想将这些列分组到一个新的div中。

我让一位朋友为我调查此事,他带着这个来回来,但我仍然无法让它发挥作用。如果有人能提供任何帮助,我们将不胜感激。

$.fn.gridRows = function() {
    var cumulativeWidth = 0;
    var items = [];
    $('.column',this).each(function(index){
        var col = $(this);
        col.data('index', index);
        var percentageWidth = (100 * parseFloat(col.css('width')) / parseFloat(col.parent().css('width')));
        cumulativeWidth += percentageWidth;
        items.push(index);
        if(cumulativeWidth >= 100){
            if(items.length == 1){
                col.wrap('<div></div>');
            }else{
                var selector = '*' + items.join('][data-index=').substring(1) +']';
                $(selector).wrap('<div></div>');
            }
            items = [];
            cumulativeWidth = 0;
        }
    });
}

$(document).ready(function() {
    $('body .group').gridRows();
});

1 个答案:

答案 0 :(得分:0)

我已经改变了一下,但这对我有用。至少,它将列分组为总宽度不超过100%的框!

$.fn.gridRows = function() {
    var cumulativeWidth = 0,
        columns = $('.column',this),
        rowItems = [];

    var group = function(items) {
        if (items.length) {
            $('<div></div>').insertBefore(items[0]).append(items);
        }
    }

    for (var i = 0, l = columns.length; i < l; ++i) {
        var $column = $(columns[i]),
            width = Math.round(100/$column.parent().width() * $column.width());

        if (cumulativeWidth + width > 100) {
            group(rowItems);
            cumulativeWidth = 0;
            rowItems = [];
        }
        cumulativeWidth += width;
        rowItems.push($column[0]);
    }

    group(rowItems);
}