表格滚动与固定第一列

5

我希望在按钮点击时使表格左右滚动,同时保持第一列的位置不变。由于我的数据全部在一个表格中,所以无法创建两个表格代替一个。是否有任何方法可以实现这一点?请参见下面的fiddle。

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代码

考虑使用纯CSS解决方案:https://dev59.com/jGUo5IYBdhLWcg3wvBeX - Avatar
2个回答

3

这里是一个可工作的Fiddle

使用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而不是表格本身。


哦..我刚刚手动滚动了滚动条,没有看到按钮。我会修复它的..稍等一下。 - Rajshekar Reddy

0
如果您的表格更加复杂,无法使用固定大小的列,则需要使用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());

我同意,我的答案并没有真正解决主要问题,但当我寻找修复表格列的解决方案时,我没有找到任何解决方案,所以我决定在这里发布我的解决方案。 实际上,为了解决问题,您只需要像我一样添加自动滚动逻辑即可。 感谢提及这个错误,我现在就去编辑答案。 - RomanMitasov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接