I have a html table that always shows its header columns, when the user scrolls the windows. It works fine, but the header (thead) is always aligned left; when the table is narrow and centered, the columns don't match anymore the header columns. This also happens when the table is very wide and has many columns, forcing the horizontal scroll to appear; the header doesn't scroll, and always the first columns are displayed.
JavaScript:
function moveScroll(){
var scroll = $(window).scrollTop();
var anchor_top = $("#main_table").offset().top;
var anchor_bottom = $("#bottom_anchor").offset().top;
if (scroll > anchor_top && scroll < anchor_bottom)
{
clone_table = $("#clone");
if(clone_table.length == 0)
{
clone_table = $("#main_table").clone();
clone_table.attr('id', 'clone');
clone_table.css({position:'fixed', 'pointer-events': 'none', top: 0});
clone_table.width($("#main_table").width());
$("#table_container").append(clone_table);
$("#clone").css({visibility:'hidden'});
$("#clone thead").css({visibility:'visible'});
}
}
else
{
$("#clone").remove();
}
}
$("#main_table").wrap('<div id="table_container"></div>');
$('<div id="bottom_anchor"></div>').insertAfter('#main_table');
$(window).scroll(moveScroll);
HTML:
<table id="main_table" align="center">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tr>
<td>Column</td>
<td>Column</td>
<td>Column</td>
<td>Column</td>
</tr>
<tr>
<td>Column</td>
<td>Column</td>
<td>Column</td>
<td>C开发者_如何学Pythonolumn</td>
</tr>
</table>
CSS:
body {
width: 500px;
}
thead tr {
background-color: lightgrey;
}
How can I fix this?
Preview horizontal scroll problem
Preview narrow centered table - solved
http://jsfiddle.net/AvaUU/7/
Add in:
.css({
position: 'fixed',
'pointer-events': 'none',
left: $("#main_table").offset().left+'px',
top: 0
})
(Oh, and I chained a lot of your jQuery together, just because I like how that looks.)
精彩评论