jquery UI Sortable with table and tr width

前端 未结 12 781
不知归路
不知归路 2020-11-28 18:02

I am using jQuery UI sortable to make my table grid sortable. The code seems to work fine but because I am not adding width to tds, when I drag the tr

12条回答
  •  一向
    一向 (楼主)
    2020-11-28 18:46

    The selected answer here is a really nice solution, but it has one severe bug which is apparent in the original JS fiddle (http://jsfiddle.net/bgrins/tzYbU/): try dragging the longest row (God Bless You, Mr. Rosewater), and the rest of the cell widths collapse.

    This means that fixing the cell widths on the dragged cell is not enough - you also need to fix widths on the table.

    $(function () {
        $('td, th', '#sortFixed').each(function () {
            var cell = $(this);
            cell.width(cell.width());
        });
    
        $('#sortFixed tbody').sortable().disableSelection();
    });
    

    JS Fiddle: http://jsfiddle.net/rp4fV/3/

    This fixes the problem of the table collapsing after you drag the first column, but introduces a new one: if you change the content of the table the cell sizes are now fixed.

    To work around this when adding or changing content you would need to clear the widths set:

    $('td, th', '#sortFixed').each(function () {
        var cell = $(this);
        cell.css('width','');
    });
    

    Then add your content, then fix widths again.

    This still isn't a complete solution, as (especially with a table) you need a drop placeholder. For that we need to add a function on start that builds the placeholder:

    $('#sortFixed tbody').sortable({
        items: '> tr',
        forcePlaceholderSize: true,
        placeholder:'must-have-class',
        start: function (event, ui) {
            // Build a placeholder cell that spans all the cells in the row
            var cellCount = 0;
            $('td, th', ui.helper).each(function () {
                // For each TD or TH try and get it's colspan attribute, and add that or 1 to the total
                var colspan = 1;
                var colspanAttr = $(this).attr('colspan');
                if (colspanAttr > 1) {
                    colspan = colspanAttr;
                }
                cellCount += colspan;
            });
    
            // Add the placeholder UI - note that this is the item's content, so TD rather than TR
            ui.placeholder.html(' ');
        }
    }).disableSelection();
    

    JS Fiddle: http://jsfiddle.net/rp4fV/4/

提交回复
热议问题