How to easily add/remove cells from a Table (Shifting existent cells)

前端 未结 2 1827
挽巷
挽巷 2021-01-15 01:17

I want a table to automatically align cells to be two per row, meaning that if a add/remove a cell, cells will shift to be two per row (with one on last row if total number

2条回答
  •  执笔经年
    2021-01-15 01:26

    I'll show you three ways to accomplish what you need,

    • css3 Using flex (modern browsers only)
    • css Using inline-table (problem with cell height but usable as sort-of fallback)
    • jquery Using standard (All browsers!)

      Using CSS3's FLEX

      .table{
        display: flex;
        flex-wrap: wrap;
      }
      .cell{
        width:50%;
        background:#ffffd;
      }
      NEW
      OLD1
      OLD2
      OLD3
      new line
      OLD4

      Using inline-table (issue with cell height)

      display: table;   for the parent element and
      display: inline-table for the inner DIVs:

      .table{
        display:table;
      }
      .cell{
        display:inline-table;
        width:50%;     /* With percentage you simulate "how-many-per-Row" */
        background:#ffffd;
      }
      NEW
      OLD1
      OLD2
      OLD3
      new line
      OLD4

      You could use the inline-table as a fallback for older browsers - it's not the exact same result but without JavaScript it's the best you could get.

      Take a look in the specs about the display property: https://developer.mozilla.org/en-US/docs/Web/CSS/display


      Using

      , and ") ); } // Shift all last TD's to the next row: $table.find("tr:not(:last)").each(function(){ var $tdLast = $(this).find("td").last(); $(this).next("tr").prepend( $tdLast ); }); // Finally. Prepend the new TD element to the first TR $table.find("tr").first().prepend( $newCell ); } $("button").on("click", prependNewCell); });
      td{
        width:50%;
        background:#ffffd;
      }
      
      
      
      
      and JavaScript (jQuery)

      If you want to stick to good 'ol table elements you can use "a bit" of jQuery.
      In that case it's a bit more complicated (see code-comments):

      jQuery(function($){ // DOM is now ready
      
        var $table = $("table"); // Get your table
        var maxRowCells = 2;     // only 2-per-Row
        var counter = 0;         // just a dummy counter
      
        function prependNewCell(){
      
          var $newCell = $("
      ", {html: "NEW"+(++counter)}); // Is the last row full? if($table.find("tr:last td").length == maxRowCells){ // If true, append a new TR to TABLE to shift TD's to $table.append( $("
      OLD1 OLD2
      OLD3 OLD4

提交回复
热议问题