【问题标题】:Creating two-way fixed scrolling of table headers创建表头的双向固定滚动
【发布时间】:2013-11-16 12:48:27
【问题描述】:

我有一个巨大的表格,其中包含垂直和水平方向的数据...

像这样:jsfiddle

我希望固定最左边的列和顶行,以便当我在两个方向滚动时,我能够将这两个(列和行)保持在适当的位置。但只移动内容。

如何用 JS/CSS 实现这一点?

我猜一个纯 css 解决方案不会这样做,因为有一个双向滚动。

someclass { position: fixed } 

【问题讨论】:

  • 这不会导致标题不再准确吗?如果向右滚动一列,标题将保持原位,内容将向左移动一列,导致第二个内容列位于第一个标题列下方。
  • 如果我的想法是正确的,顶行应该垂直固定,水平固定。左列应水平固定,垂直固定。 (?)
  • 您可能对此感兴趣。 stackoverflow.com/questions/11891065/…
  • @TreeTree 谢谢你,我认为有些代码是可重用的。不过我不是 JS 大师。
  • 看第一个答案,根本没有javascript。

标签: javascript jquery css


【解决方案1】:

回答您的问题所需的整个代码太大,无法在此处包含。相反,我会将您链接到包含答案的 JSBin,并且只包含样式和 javascript。

注意事项是:

  • 如果您一心想要使用表格而不是 div 来显示数据,那么您将很难格式化我给您的答案,尤其是当单元格中的数据具有不同的宽度和高度时。
    • 为了实现这一点,您必须检查每一行和每一列的标题,然后将它们各自的宽度和高度设置为它们的宽度/高度与表格中行的宽度/高度之间的最大值。它们的宽度和高度不会自动设置为与表格中的其余单元格相对应的原因是因为在设置它们的position: fixed 样式属性时,您基本上会将它们从表格中分离出来。
      • 因此,如果您有能力,请考虑使用 div 代替并将行标题拆分为单独的 div,您可以 position: fixed 并模拟列标题的当前行为
      • 另一个好处是您将获得性能提升,因为 jQuery 不会在您每次滚动时遍历每一行来调整行标题。
  • 您必须使用jQuery UI

HTML:

<!-- Notice I removed background and border color from table tag -->
<table border="0" width="100%" cellpadding="3" cellspacing="1">
  <tr>
    <td>Dead Cell</td><!-- this cell is not shown -->
    ...

CSS:

/* Make white space above table since we broke the column headers out of the table */
table {
  margin-top: 51px;
  position: relative;
}
table td {
  border: 1px solid #FFCC00;
  height: 44px;
  background-color: #FFFFCC;
}
/* styling for column headers */
table tr:first-child {
  position: fixed;
  top: 0;
  left: 57px;
  z-index: 100;
}
/* remove first cell in top left position */
table tr:first-child td:first-child {
  display: none;
}
table tr:first-child td,
table tr {
  position: relative;
}
table tr:first-child td {
  background: orange;
}
table tr td:first-child {
  background: orange;
  position: fixed;
  width: 39px
}
/* Make white space to the left of table since we broke the row headers out of the table */
table tr:nth-child(n+2) td:nth-child(2) {
  margin-left: 48px;
  display: block;
}

JS:

$(function(){ // When document is loaded and ready
  $(window).scroll(function() { // When we scroll in the window
    // Move column headers into place
    $('table tr:first-child td').css('left', - $(this).scrollLeft());
    // Move row headers into place
    $('table tr td:first-child').each(function() {
      $(this).position({ // jQuery UI overloaded function
        my: "left top",
        at: "left top",
        of: $(this).parent(),
        using: function(pos) {
          $(this).css('top', pos.top);
        }
      });
    });
  });
});

同样,这里是JSBin 的链接。

【讨论】:

  • 非常感谢!我会试试这种情况。
  • 2008 年左右我们尝试回溯时,刚刚和一位同事回忆起这有多么困难。我们当时放弃了并使用了闪存。尝试在 IE6 中执行此操作! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 2021-10-26
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2020-05-21
相关资源
最近更新 更多