具有固定第一列的表滚动

时间:2016-03-18 15:38:03

标签: jquery html css

我正试图让桌子在按钮上左/右滚动点击,保留第一列的位置。 我的数据都在一个表中,因此我无法创建两个表而不是一个表。有没有办法做到这一点?见下面的小提琴。

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

2 个答案:

答案 0 :(得分: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有滚动而不是表格。

答案 1 :(得分: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
});
相关问题