[关闭]
@TedZhou 2016-05-10T07:51:46.000000Z 字数 596 阅读 233

让table固定表头的一种实现方法

html css javascript 技术


不说废话了,直接上code:)

.html

  1. <!--把table放到div容器里。-->
  2. <div class="table-container">
  3. <table class="table-fixed">
  4. <thead>
  5. <tr><th>column1</th>...略...</tr>
  6. </thead>
  7. <tbody>....略...</tbody>
  8. </table>
  9. <div>

.css

  1. <style>
  2. /*限制容器高度并允许滚动*/
  3. .table-container{
  4. max-height: 200px;
  5. overflow: auto;
  6. }
  7. /*表头cell设为相对定位*/
  8. .table-fixed>thead>tr>th{
  9. position:relative;
  10. }
  11. </style>

.js

  1. <script>
  2. $(function(){
  3. //容器滚动时,把表头cell的top设为scrollTop,以实现fixed效果
  4. $('.table-container').scroll(function(){
  5. $(this).find('.table-fixed>thead>tr>th').css('top',this.scrollTop);
  6. });
  7. });
  8. </script>

总结

相较于表头和内容分离的做法,这种实现方式不会出现对不齐的问题,而且比较简单(:不想写js的请忽略)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注