jQuery 滚动时表头需要保持固定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18644021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Table header needs to remain fixed during scrolling
提问by cdub
I have a table with a header and a body, and I want the table header to remain fixed while scrolling happens on the body.
我有一个带有标题和正文的表格,我希望表格标题在正文上发生滚动时保持固定。
The table is set up like so:
该表设置如下:
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
...more rows for data...
</tbody>
The table is encapsulated with a and has CSS like:
该表用 a 封装并具有如下 CSS:
overflow-x: hidden;
overflow-y: auto;
height: 400px;
I need the table header to remain perfectly still but when I add position: fixed; to thead or to the individual th the header gets squished.
我需要表头保持完全静止,但是当我添加 position: fixed; 到头或个人头被压扁。
Whats the best approach for this?
最好的方法是什么?
回答by mkoryak
i just updated a plugin that I wrote that does this exact thing:
我刚刚更新了一个我写的插件,它可以做这件事:
http://mkoryak.github.io/floatThead/
http://mkoryak.github.io/floatThead/
it may be what you need
它可能是你需要的
回答by Jason
If you need your tables to contain any dynamic data so that you can't specify width, you'll have to use a JS/jQuery solution like the following:
如果您需要您的表格包含任何动态数据,以便您无法指定宽度,则必须使用如下所示的 JS/jQuery 解决方案:
Table header to stay fixed at the top when user scrolls it out of view with jQuery
当用户使用 jQuery 将其滚动到视图之外时,表头保持固定在顶部
If you know exactly what is going to be displayed though and don't mind making some tweaks/hacks, you can just make your thead
position:fixed
, then mess with the spacing until it looks good.
如果您确切地知道将要显示的内容并且不介意进行一些调整/修改,您可以只制作您的thead
position:fixed
, 然后弄乱间距,直到它看起来不错。
Take a look at this jsFiddle to see what I mean.
EDIT: Here's an updated jsFiddle that's spaced a little better, because OP was too lazy to type in a few characters for himself and expects others to do everything for him.
编辑:这是一个更新的 jsFiddle,间隔更好一点,因为 OP 懒得为自己输入几个字符,并希望其他人为他做一切。