【问题标题】:Table scroll with fixed first column具有固定第一列的表格滚动
【发布时间】:2016-07-05 10:49:48
【问题描述】:

我正在尝试让表格在按钮单击时向左/向右滚动,以将第一列保持在原位。 我的数据都在一个表中,所以我不能创建两个表而不是一个表。有没有办法做到这一点?请参阅下面的小提琴。

jQuery:

$(document).ready(function() {
  $("#right").on("click", function() {
    var position = $("table").position();
    $("table").animate({
      left: position.left - 200
    }, 800);
  });
});
$("#left").on("click", function() {
var position = $("table").position();
 $("table").animate({
   left: position.left + 200
 }, 800);
});

CSS:

#table-wrapper {
width: 95%;
float: left;
overflow-x: scroll;
background: #ddd;

}

table {
 background: #fff;
 width: 1200px;
 text-align:center;
 overflow: hidden;
 position:relative;
}
table thead tr th:first-child,
table tbody tr td:first-child {
 background: yellow;
 top: auto;
 left: 0.5;
 position: absolute;
 width: 6em;
}

HTML:

<button id="left">&larr;</button>
<button id="right">&rarr;</button>

<div id="table-wrapper">
  <table border="1">
    <thead>
      <tr>
        <th>Heading1</th>
        <th>Heading2</th>
        <th>Heading3</th>
        <th>Heading4</th>
        <th>Heading5</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>12</td>
        <td>13</td>
        <td>14</td>
        <td>15</td>
      </tr>
      <tr>
        <td>2</td>
        <td>22</td>
        <td>23</td>
        <td>24</td>
        <td>25</td>
      </tr>
      <tr>
        <td>3</td>
        <td>32</td>
        <td>33</td>
        <td>34</td>
        <td>35</td>
      </tr>
    </tbody>
  </table>
</div>

这是我的fiddle

【问题讨论】:

标签: jquery html css


【解决方案1】:

这里是Working Fiddle

使用这个 css position:fixed 来修复元素。

进行下面提到的更改

table thead tr th:first-child,
table tbody tr td:first-child {
  background: yellow;
  top: auto;
  position:fixed;  /*change this*/
  left: 0.5;
  width: 6em;
}

您还必须稍微更改一下您的 Jquery。问题在于选择器。

在您的 Jquery 中,将 $("table") 替换为 $("#table-wrapper"),因为它的 table-wrapper 具有滚动而不是表格。

【讨论】:

  • 哦.. 我只是手动滚动了滚动条,没有看到按钮。我会修复它.. 一会儿
【解决方案2】:

如果你的表格比较复杂,并且无法制作固定大小的列,你需要使用jQuery解决方案,而不仅仅是CSS。

我花了一些时间解决了同样的问题,并找到了TableHeadFixer jQuery 插件。但它可能不起作用,所以我制作了自己的版本 - TableFixer。你可以这样使用它:

$('#table').tableFixer({
  head: false, // true for header fix
  foot: false, // true for footer fix
  left: 1, // number of fixed columns on the left
  right: 0, // number of fixed columns on the right
});

然后,在按钮单击事件处理程序中添加一些滚动逻辑:

$('#table-wrapper').scrollLeft($('#table-wrapper > table').width());

【讨论】:

  • 我同意,我的回答并没有真正解决主要问题,但是当我寻找修复表格列的解决方案时,我没有找到任何解决方案,所以我决定在这里发布我的解决方案。实际上,要解决问题,您只需要像我一样添加自动滚动逻辑即可。感谢您提到这个错误,我现在要编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 2018-01-26
  • 1970-01-01
  • 2020-07-24
  • 2014-03-07
相关资源
最近更新 更多