2016-04-25 75 views
1

假设我有以下几点:使用Bootstrap使一列固定为水平滚动?

  <table class="table table-bordered table-striped table-hover"> 
      <thead> 
      <tr> 
       <th>#</th> 
       <th>Table heading</th> 
       <th>Table heading</th> 
       <th>Table heading</th> 
       <th>Table heading</th> 
       <th>Table heading</th> 
       /* ... more table headers */ 
      </tr> 
      </thead> 
      <tbody> 
      <tr> 
       <td>ID 1</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
      </tr> 
      <tr> 
       <td>ID 2</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
       <td>Table cell</td> 
      </tr> 
       /* ... more table rows */ 
      </tbody> 
     </table> 

我想添加更多的表头,并最终使该表可滚动水平。是否有可能使第一列(包含ID的列)保持固定并始终可见,无论用户水平滚动多少?

我想创建使用jQuery插件已经在这里实现:http://www.novasoftware.com/Download/jQuery_FixedTable/JQuery_FixedTable.aspx(现场演示这里:http://www.novasoftware.com/Download/jQuery_FixedTable/jQuery_FixedTable_Demo.htm

回答

3

你想要做的是设置你的第一列的位置absolute什么。这将需要应用于您所有行中的第一个<td>标签 - 轻松完成课程。这也需要一个宽度,然后一个与宽度相等的负左边距,以便它放在滚动内容的左侧。

然后您需要为您的表创建一个包装,并将其overflow-x设置为scroll。这允许您的表格滚动。这也需要一个宽度 - 超出宽度的任何东西都可以滚动。

您可能想要做的最后一件事是将white-space: nowrap添加到您的<th><td>元素中,以便单元格中的文本不会换行。

Demo Here

th, td { 
    white-space: nowrap; 
} 

.first-col { 
    position: absolute; 
    width: 5em; 
    margin-left: -5em; 
} 

.table-wrapper { 
    overflow-x: scroll; 
    width: 600px; 
    margin: 0 auto; 
} 

<div class="container"> 
    <div class="table-wrapper"> 
     <table class="table table-bordered table-striped table-hover"> 
      <thead> 
       <tr> 
        <th class="first-col">#</th> 
        <th>Table heading</th> 
        <th>Table heading</th> 
        <th>Table heading</th> 
        <th>Table heading</th> 
        <th>Table heading</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr> 
        <td class="first-col">ID 1</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
       </tr> 
       <tr> 
        <td class="first-col">ID 2</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
        <td>Table cell</td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
</div> 
+1

嘿棘手,非常感谢你为你的迅速和非常有益的反应! – Sparks