You can use Lobstrosity's code with a slight modification: position: fixed
instead of absolute
.
position: fixed
is now widely adopted by all browsers including IE8 and onwards. BTW fixed renders much nicer on mobile/tablet devices than position: absolute
.
I found that on a table with dynamic widths for each column, the absolutely positioned <thead> would lose the widths of the rest of the columns, so to fix this I came up with the following code:
What this code does is as follows:
Determines the widths of each column in your table by looking up the CSS widths of the first <tbody> <tr> <td> row and storing these in an array for later. When the user scrolls the class 'fixed' is added to the <thead> (Default browser behaviour will alter the widths of the <th>'s and they won't match up with the <tbody>. So to fix this we retroactively set the widths of the <th> to the values we've read earlier.
Anyway here's the code:
CSS
table.entries {width: 100%;border-spacing: 0px;margin:0;}
table.entries thead.fixed {position:fixed;top:0;}
HTML
<table class="entries" id="entriestable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Location</th>
<th>DOB</th>
<th>Opt in</th>
<th>Added</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">Ricky Bobby</td>
<td>[email protected]</td>
<td class="addy"><i>Kent, GB</i></td>
<td class="dob">20/08/1984</td>
<td>Yes</td>
<td class="date">4 hours ago</td>
</tr>
</tbody>
</table>
JavaScript
TableThing = function(params) {
settings = {
table: $('#entriestable'),
thead: []
};
this.fixThead = function() {
// empty our array to begin with
settings.thead = [];
// loop over the first row of td's in <tbody> and get the widths of individual <td>'s
$('tbody tr:eq(1) td', settings.table).each( function(i,v){
settings.thead.push($(v).width());
});
// now loop over our array setting the widths we've got to the <th>'s
for(i=0;i<settings.thead.length;i++) {
$('thead th:eq('+i+')', settings.table).width(settings.thead[i]);
}
// here we attach to the scroll, adding the class 'fixed' to the <thead>
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (windowTop > settings.table.offset().top) {
$("thead", settings.table).addClass("fixed");
}
else {
$("thead", settings.table).removeClass("fixed");
}
});
}
}
$(function(){
var table = new TableThing();
table.fixThead();
$(window).resize(function(){
table.fixThead();
});
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…