响应式表格之固定表头的简单实现

(编辑:jimmy 日期: 2024/10/3 浏览:2)

数据展示时,表头的固定,可以有更好的可读性。

一、实现方式:

1、定义2个表格,一个absolute固定

<div class="table1-wapper"> 
  <table width="100%" cellpadding="0" cellspacing="0" id="table1"> 
   <tr><th><div>序号</div></th><th><div>股票名称</div></th>...</tr> 
    <tr>...</tr> 
 </table> 
</div> 
 <div class="fixed-table1-wapper"> 
 <table width="100%" cellpadding="0" cellspacing="0" id="fixed-table1"> 
 </table> 
</div> 

2、表1<th>复制,并插入表2

var th_new=$("#table1 tr").eq(0).clone(); 
$("#fixed-table1").append(th_new); 

3、resize()方法,实时获取表1各列<th>宽度

function trResize(){ 
  $("#fixed-table1 th").each(function(){ 
  var num=$(this).index(); 
  var th_width=$("#table1 th").eq(num).width(); 
  $(this).css("width",th_width+"px"); 
  }); 
} 

4、页面过小时,表格滚动带表头滚动

$(".table1-wapper").scroll(function(){ 
  var scroll=-$(this).scrollLeft() 
  $(".fixed-table1-wapper").css("left",scroll+"px"); 
}); 

二、注意细节:

1、宽度自适应、去除单元格间隙:
<table width="100%" cellpadding="0" cellspacing="0" ></table>

2、表格线:
直接<td>添加border,会出现边线重合;添加属性:border-collapse: collapse;

响应式表格之固定表头的简单实现

3、td宽度:

控制第一行宽度即可 <td width="70"></td> / <td width="20%"></td>

4、奇偶行颜色不同:

css: #table1 tr:nth-child(2n){background-color:#ccc;} ie7兼容性问题

jquery: $("#table1 tr:even").css("background-color","#ccc");

以下为完整代码:

<!doctype html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>表格整理</title> 
<link rel="stylesheet" type="text/css" href="css/basic.css"> 
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-1.8.3.min.js">

以上这篇响应式表格之固定表头的简单实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。