1、CSS
<style type="text/css"> #scroll_head { position: absolute; display: none; } </style>
2、Javascript
<script type="text/javascript">
//該函數在上面一個table數據加載完成后調用
//把表頭的寬度設置到會滾動的頁頭去
var copyWidth = function () {
var b = $('#data_tbody').prev().find('tr:last').find('th');
var c = $('#scroll_head').find('tr:last').find('th');
for (var i = 0; i < b.length; i++) {
var newWith = b.eq(i).width();
if ($.browser.msie) {
newWith += 1;
}
c.eq(i).width(newWith);
}
}
$(function () {
$(window).scroll(function () {
if ($('#data_tbody').length > 0) {
var thead = $('#data_tbody').prev();
var thOffset = thead.offset();
var scTop = $(window).scrollTop(); //滾動條相對top的位置
if (scTop > thOffset.top) { //滾動條滾到thead及以下的位置,用臨時的thead代替顯示
$('#scroll_head').css('display', 'block');
$('#scroll_head').offset({ top: scTop, left: thOffset.left });
}
else { //滾動條滾到thead上的位置,用table的原始thead顯示
$('#scroll_head').css('display', 'none');
}
}
});
});
</script>
3、Html內容
<div id="data_div"> <table> @*thead內容及樣式同scroll_head中的thead*@ @*thead使用深背景色,避免滾動時和tbody內容重疊顯示*@ <thead> <tr> @*一級標題*@ <th class="tt1" colspan="2">一級1</th> <th class="tt2" colspan="5">一級2</th> <th class="tt3" colspan="6">一級3</th> </tr> <tr> @*二級標題*@ <th style="width: 23px;">二級11</th> <th style="width: 36px;">二級12</th> <th class="tt" style="width: 40px;">二級21</th> <th class="tt" style="width: 30px;">二級22</th> <th class="tt" style="width: 30px;">二級23</th> <th class="tt" style="width: 30px;">二級23</th> <th class="tt" style="width: 30px;">二級24</th> <th class="tt" style="width: 30px;">二級25</th> <th class="tt" style="width: 30px;">二級31</th> <th class="tt" style="width: 30px;">二級32</th> <th class="tt" style="width: 30px;">二級33</th> <th class="tt" style="width: 30px;">二級33</th> <th class="tt" style="width: 30px;">二級34</th> <th class="tt" style="width: 30px;">二級35</th> <th class="tt" style="width: 30px;">二級36</th> </tr> </thead> <tbody id="data_tbody"> 數據內容,在數據加載完成后調用copyWidth()函數解決兼容性 </tbody> </table> </div> <div id="scroll_head" style="display:block; top: 168px; left: 0px; position: relative;"> <table width="100%"> <thead> @*thead使用深背景色,避免滾動時和tbody內容重疊顯示*@ <tr> @*一級標題*@ <th class="tt1" colspan="2">一級1</th> <th class="tt2" colspan="5">一級2</th> <th class="tt3" colspan="6">一級3</th> </tr> <tr> @*二級標題*@ <th style="width: 23px;">二級11</th> <th style="width: 36px;">二級12</th> <th class="tt" style="width: 40px;">二級21</th> <th class="tt" style="width: 30px;">二級22</th> <th class="tt" style="width: 30px;">二級23</th> <th class="tt" style="width: 30px;">二級23</th> <th class="tt" style="width: 30px;">二級24</th> <th class="tt" style="width: 30px;">二級25</th> <th class="tt" style="width: 30px;">二級31</th> <th class="tt" style="width: 30px;">二級32</th> <th class="tt" style="width: 30px;">二級33</th> <th class="tt" style="width: 30px;">二級33</th> <th class="tt" style="width: 30px;">二級34</th> <th class="tt" style="width: 30px;">二級35</th> <th class="tt" style="width: 30px;">二級36</th> </tr> </thead> </table> </div>
