设置动态宽度

时间:2017-08-30 19:50:48

标签: jquery css

我想知道如何获得th的宽度并将此标题下的所有td设置为相同的宽度。下一个th的宽度不同,此td下的所有th都是适当的宽度,与第一个不同。基本上尝试将我的theadtbody列相对于彼此排列。

我桌子的结构是:

<table id="my_table">
     <thead>
        <tr>
          <th></th>
          <th></th>
          <th></th>
        </tr>
     </thead>
     <tbody>
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
     </tbody>
</table>

可滚动表格的CSS如下:

#my_table thead, #my_table tbody {
        display: inline-block;
        overflow: auto;
        width: 100%;
    }

    #my_table thead{
        height: 100px;
    }

    #my_table tbody{
        height: 300px;
    }

进入的数据是动态的,每次都会使单元格的宽度不同。

使用jQuery,我不知道如何遍历每个th并将宽度分配给相应的td

var table = document.getElementById('#my_table');

table.find('th').each(function() {
    var header_width = this.width();
    $table.width(header_width);
});

虽然这不起作用。我觉得好像我错误地使用了each()函数。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

Try this, is ugly and is not efficient but should do what you want to do:

Access-Control-Expose-Headers

Note: I didn't check the syntax, so it may contain a bug.

答案 1 :(得分:0)

第一。首先将th长度(按字母长度)相加,然后按%长度的th更新宽度,请参阅下面的示例: 第2位。用<div class="scrollable">和css:

包装你的内容
.scrollable{
  height: 200px;
  overflow: scroll;
}

这允许您控制td的高度而不设置tbody到内联块,这会破坏布局。

$(window).resize(function() {
  var total_len = $('thead tr th').text().length;
  $('thead tr th').each(function() {
    pct = $(this).text().length / total_len * 100;
    $(this).width(pct + '%');
  })
}).trigger('resize');
table * {
  border: 1px solid black;
}

table {
  width: 100%;
  display: table;
}

table * {
  border: 1px solid red;
  text-align: center;
}

#my_table thead tr {
  height: 100px;
}

.scrollable{
  height: 200px;
  overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
  <thead>
    <tr>
      <th>111 121312312 21 1211 31123121</th>
      <th>2222 2 22 22</th>
      <th>3333 </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><div class="scrollable">tests 11 1 1 1 1 1 111 1 1 1 1 1</div></td>
      <td><div class="scrollable">2 2 2 22 2</div></td>
      <td><div class="scrollable">I am wondering how to get the width of a th and set all of the td under this header to be the same width. Next th would be a different width and all of the td under this th would be that appropriate width, different from the first. Essentially trying
        to line up my thead and tbody columns relative to eachother.</div></td>
    </tr>
    <tbody>
</table>

答案 2 :(得分:-1)

Just change each th width to a fixed width with css:

$(dat).each( function() { ...
<count1>

P.S. Add max-width instead of width to allow them to expand (as much as possible)