Scrollable table ideas (tricky)
I've been wrestling with this for some time now. Say that I have a table that has many rows and many columns (overflows the page vertically and horizontally). I开发者_运维问答 want to fix the first row (thead) in place.
The catch: I want the vertical and horizontal scrollbars to ALWAYS be visible. i.e., I don't want the user to have to scroll horizontally to find the vertical scroll bar, and vice versa.
The best I could come up with is to split the thead and tbody into two separate tables with synchronized scrolling, but this creates problems with alignment and matching cell widths, so I'd rather not.
How would you go about solving this?
No need to split the the table into 2 tables. You can try the following which uses one table but still freezes the header.
<table >
<thead><tr><th>This is my header</th></tr></thead>
<tbody style="max-height:100px;overflow:auto;display:block">
<tr>
<td>col1</td>
</tr>
<tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr><tr>
<td>col1</td>
</tr>
</tbody>
</table>
I use the jquery datatables plugin, an example of what you want can be seen here http://www.datatables.net/examples/basic_init/scroll_xy.html
To anyone who wants to achieve a similar effect:
Wrap your table in a div with width:100%;
and overflow:auto;
.
Copy the header portion of your table and create a new table with just that in it. POSITION THIS TABLE AS ABSOLUTE! (position:absolute;
)
Place your header table in the same div as the real table. (It should fit perfectly over the original header portion).
Use jQuery to manage the scrolling of the div and stick the header in place...
jQuery(document).ready(function() {
jQuery('#tableDiv').scroll(function() {
jQuery('#copiedHeaderTable').css('top', jQuery(this).scrollTop());
});
})
This solution of course makes a few assumptions about your requirements, but has a few advantages (simplicity being the main).
Edit To ensure matching cell widths, wrap all th contents in a div and set the width of each div manually before the cloning:
jQuery('#headerRow th div').each(function() {
jQuery(this).css('width', jQuery(this).parent()[0].offsetWidth+'px');
});
精彩评论