使用JS的表标题滚动

时间:2018-12-26 12:32:51

标签: javascript html css

嗨,我正在处理两个表,一个表具有表头,另一个表具有表主体。需要固定表头和两个表内容正确对齐的帮助。在修复标题时,我随后无法对齐表内容对此。在id的帮助下,我修复了表头。任何人都可以修复此对齐方式。谢谢。

res$mbo.result$opt.path

Here is the Demo

1 个答案:

答案 0 :(得分:0)

您想在滚动表(原始表)的顶部显示固定 thead(克隆表)。

查看此有效演示CODEPEN demo

这是您要找的东西吗?运作方式:

HTML部分:

<!-- a CONTAINER for everything -->
<div id="table-holder">
  <!-- a fixed TOP that is visible or hidden on scroll -->
  <div id="table-top">
    <!-- a TABLE CLONE that contains the THEAD -->
    <table id="table-clone" border="1"></table>
  </div>
  <!-- a CONTAINER that allows the original table to scroll -->
  <div id="table-scroll">
    <!-- the ORIGINAL TABLE -->
    <table id="table-original" border="1">
      <!-- the THEAD -->
      <thead>....</thead>
      <!-- the TBODY -->
      <tbody>....</tbody>
    </table>
  </div><!-- endof: #table-scroll -->
</div><!-- endof: #table-holder -->

CSS部分:

#table-holder {
  position:relative;
}
#table-top {
  width:100%;  /* important */
  position:absolute;  /* important -> always at top */
  display:none;  /* hidden at first */
}
#table-scroll {
  float:left;
  width:100%;
  height:100%;
  overflow-y:scroll; /* important */
}
table {
  width:100%;
}

JS部分(jQuery):

// set main table html vars
var $table_top = $("#table-top");
var $table_scroll = $("#table-scroll");
var $table_clone = $("#table-clone");
var $thead_original = $("#table-original thead");
var $thead_clone = $thead_original.clone();
// copy the original THEAD into table-top
$table_clone.append($thead_clone);
// adjust table-top width (consider the width of the Y scrollbar)
$table_top.css("width", $thead_original.width())
// set vars needed to show/hide table-top
var thead_height = $thead_original.height();
//// set the threshold for the show/hide action
var visible_top = $table_scroll.offset().top;
var table_top_visible = 0;
// set onScroll action: show/hide table-top
$table_scroll.on("scroll",function(){
  // the the current offset of the original THEAD
  var thead_top = $thead_original.offset().top;
  //// get the position of the bottom of the THEAD
  var thead_bottom = thead_top + thead_height;
  // check if the original THEAD is hidden
  if (thead_bottom < visible_top) {
    // if the original is hidden -> show the clone
    if (!table_top_visible) {
      table_top_visible = 1;
      $table_top.fadeIn();
    }
  } else {
    // else, the original is visible -> hide the clone
    if (table_top_visible) {
      table_top_visible = 0;
      $table_top.fadeOut();
    }
  }
});