具有从原始开始的绝对宽度的克隆固定头

时间:2018-09-06 14:54:00

标签: javascript jquery html-table fixed-header-tables

我一直在寻找使用户向下滚动页面时<table>显示固定标题的方法。我非常接近完成此实现-通过克隆原始标题并将其附加到表中。当我在原始标题的顶部重新对齐克隆的标题时,我注意到宽度有所不同,这是由于输入到表中的动态数据可能会调整某些列的宽度。出于某种原因,我的代码未采用这些列宽,我不知道为什么?

有什么建议吗?

$(document).ready(function() {
  var table = $('#list');
  var stuck = table.find('#header');
  var start = table.offset().top;
  var clone = stuck.clone().prop('id', 'fixedHeader');
  var target_children = table.children();

  // Fetch for the width of each column in the original header and place into the new clone
  clone.children().width(function(i, val) {
    return target_children.eq(i).width(); // I believe something is broken here...
  });

  // Add the Clone to the Table
  clone.prependTo(table);

  var fixedHeader = $('#fixedHeader');
  fixedHeader.hide(); // Hide the Clone at first so it appears upon scrolling

  // When Scrolling, realign the new fixedHeader and duplicate look
  $.event.add(window, 'scroll', function() {
    var p = $(window).scrollTop();
    $(fixedHeader).css('position', (p > start) ? 'fixed' : 'static');
    $(fixedHeader).css('left', table.offset().left);
    $(fixedHeader).css('right', table.offset().right);
    $(fixedHeader).css('top', (p > start) ? '0px' : '');
    $(fixedHeader).css('width', table.width());

    // Some old Code that may be helpful
    // Add the current widths of the table's header and place into the cloned header
    //$(fixedHeader).children('tr:first').children().width(function(i, val) {
      //return table.closest('table').children('tbody').children('tr:first').children().eq(i).width();
    //});

    // Show or Hide the new cloned Fixed Header on Scroll
    if (p > start)
      fixedHeader.show();
    else
      fixedHeader.hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='list'>
  <thead id='header' class='fixed'>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
    <!-- This will be a long list of fetched data that may vary in size.
         As a consequence the column widths may be stretched depending on large words-->
    <tr>
      <td>Fetched Data 1</td>
      <td>Fetched Data 2</td>
      <td>Fetched Data 3</td>
    </tr>
  </tbody>
</table>

0 个答案:

没有答案