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

Divide columns into groups (rows) based on their cumulative width with jquery

本文关键字:jquery 使用      更新时间:2023-09-26

我有许多列(不同宽度)正在生成,我需要根据它们的宽度将它们分成组或行。每当列的累计宽度达到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();
});

我已经改变了一点,但这对我来说是有效的。至少,它将列分组到总宽度不超过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);
}