遇到一個簡單的需求:
客戶有一個表格可能有很多內容,當內容很多的時候,表格就會出現滾動條
客戶希望當表格內容很多時,只滾動表格而不滾動瀏覽器窗口
在網上找到很多相關的插件,要不就是太復雜,要不就是滿足不了我的要求
於是自己動手寫了一個簡單的JS方法
思路就是將thead里的tr克隆到tbody里然后將tbody里的首行tr跟thead里的tr大小一致
- 將thead里的表頭tr克隆並插入到tbody里
- 將插入到的tbody里的tr內容清除並移除相關屬性和大小,僅作為占位使用
- 設置tbody大小及滾動
- 重新設置thead里的表頭大小以保證跟tobdy里的首行tr大小一致
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/*自定義行強制顯示*/
#hide_tr{display: table-row!important;}
/*自定義占位,但不顯示大小及內容*/
#hide_tr *{margin-top: 0;margin-bottom: 0;padding-top: 0;padding-bottom: 0;border-top: 0;border-bottom: 0;height: 0;}
</style>
</head>
<body>
<table id="MyTable" style="width:960px;font-family:微軟雅黑;color:#000;font-size:medium;border-color:black" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>姓名</th>
<th>語文</th>
<th>數學</th>
<th>英語</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
<script src='http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js'></script>
<script>
/**
* @Author: HTL
* @Email: Huangyuan413026@163.com
* @DateTime: 2016-12-26 15:05:55
* @Description: 固定表格的表頭
* 寬度為表格的寬,高度為不含滾動條瀏覽器的高度
*/
function fix_table($obj){
if(!$obj || $obj.length<=0 || ($('html').height() - $(window).height())<0) return false;
$obj.show();
//最大高度為不包含滾動條的高度
var height = $obj.find('tbody').height() - ($('html').height() - $(window).height()) - 3;
//設置表格內容高度和寬度
$obj.find('tbody').css({'max-width': $obj.width(),'overflow':'auto','max-height':height});
//移出復制的表頭並重新添加
$obj.find("#hide_tr").remove();
//內容寬度自適應
$obj.find('thead tr th').css('width','auto');
// 表頭復制並插入到內容
$obj.find('tbody tr:first').before($obj.find('thead tr').clone());
var _th = $obj.find('thead th');
//移出內容的行信息並設置跟表頭一樣的寬度
$obj.find('tbody tr:first th').each(function(i,j){ $(this).html('').width($(_th[i]).innerWidth());});
//表格第一行內容不顯示僅占位
$obj.find('tbody tr:first').attr('id','hide_tr').css('display','table-row');
//顯示滾動條
$obj.find('tbody,thead tr,tfoot tr').css('display','block');
//表格內容寬
_th = $obj.find('tbody th');
//表頭th寬跟內容th寬一致
$obj.find('thead tr:first th').each(function(i,j){ $(this).width($(_th[i]).width());});
//頁腳th寬跟內容th寬一致
$obj.find('tfoot tr:first th').each(function(i,j){ $(this).width($(_th[i]).width());});
}
$(function(){
var html = '',tr='<tr><td>學生#index#</td><td>#1#</td><td>#2#</td><td>#3#</td></tr>';
for(var i=1;i<=100;i++){
html += tr.replace("#index#",i).replace("#1#",10).replace("#2#",20).replace("#3#",30);
}
$("#MyTable tbody").html(html);
fix_table($("#MyTable"));
});
</script>
</html>
