代码之家  ›  专栏  ›  技术社区  ›  zmbq

添加不更改列宽的表行

  •  3
  • zmbq  · 技术社区  · 6 年前

    我有一个表在没有指定列宽的情况下呈现得非常好(使用Bootstrap 4)。

    我想为每一列添加一个包含输入字段的页脚。添加页脚会更改列的宽度,并且确实会使表太宽。如何添加表格单元格并指示浏览器在计算列宽时不要使用它?

    here . 简单地评论一下 <tfoot>

    3 回复  |  直到 6 年前
        1
  •  1
  •   Mr Lister hawi    6 年前

    据我所知,没有CSS唯一的方法可以做到这一点。

    window.onload = function() {
    
      var theTable = document.querySelector('.container .col-12 .table-condensed');
      var firstRow = theTable.querySelector('thead tr').cells;
      var footElements = theTable.querySelectorAll('tfoot th *');
    
      // First, we set the widths of all the contents of the tfoot to 0 so it won't take up space
      for (var i = 0; i < footElements.length; ++i)
        footElements[i].style.width = '0';
    
      // Then we fix the widths of the columns to the widths they have now
      for (var i = 0; i < firstRow.length; ++i)
        firstRow[i].style.width = '' + firstRow[i].offsetWidth + 'px';
      theTable.style.tableLayout = 'fixed';
    
      // And finally we change the widths of the tfoot contents back to what they were
      for (var i = 0; i < footElements.length; ++i)
        footElements[i].style.width = '';
    };
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="container">
      <div class="row">
        <div class="col-12">
          <table class="table table-condensed">
            <thead>
              <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>Lengthy cell with lots of text</td>
                <td>2</td>
                <td>3</td>
              </tr>
            </tbody>
    
            <tfoot>
              <tr>
                <th><input type="text"></th>
                <th><input type="text"></th>
                <th><input type="text"></th>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

    请注意,第2列和第3列中的输入对于列来说太宽,因此它们会溢出单元格(甚至超出表),但我将留给读者作为练习。

        2
  •  2
  •   G-Cyrillus    6 年前

    bootsrap 4使用 table-sm table-condensed . 这可能还不够,您可以在CSS中声明表布局并向输入添加最大宽度:

    table {table-layout:fixed;}
    input {max-width:90%;}
    

    https://jsfiddle.net/c06tomp9/


    您还可以接受流的输入,这样它们就不会影响列宽的大小计算。

    table {border:solid;}
    tfoot tr th {position:relative;height:3.4em;/* an height needs to be set to hold the inputs unseen */}
    input {position:absolute;max-width:90%;}
    

    https://jsfiddle.net/c06tomp9/1/

        3
  •  1
  •   Programmer    6 年前

    你可以用 table-layout: fixed; 在表中,这样在添加行时列的宽度不会更改,但默认情况下,所有列的宽度都相同,如果要更改宽度,则需要显式设置宽度。