Javascript 如何在向下滚动表格时保持表格标题固定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13959500/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:16:26  来源:igfitidea点击:

How to keep table headers fixed while scrolling down a table

javascripthtmlcss

提问by user1881090

I have a jsfiddle here: http://jsfiddle.net/7vv9e/2/

我在这里有一个 jsfiddle:http: //jsfiddle.net/7vv9e/2/

In this fiddle when you open it up and you see the little demo, click on the "Add Question" button multiple times until you see a scroll bar appear next to the table.

在这个小提琴中,当您打开它并看到小演示时,多次单击“添加问题”按钮,直到您看到表格旁边出现一个滚动条。

Now what I want to happen is tht when the user scrolls, the header remainns fixed while scrolling. My question is how can this be done.

现在我想要发生的是当用户滚动时,标题在滚动时保持固定。我的问题是如何做到这一点。

Below is the css code where it displays the scroll bar for the table when the table reaches a certain height:

下面是当表格达到一定高度时显示表格滚动条的 css 代码:

#details{
    height:500px;
    overflow:auto;
}

i.e The current table you see in the demo is not the final table. There will be more columns added. So I need a solution where it could work for a table with 2 columns or a table with 5 columns it doesn't matter on the width of the column, if each column can remain it's same width without any problems while scrolling down then this could be great.

即您在演示中看到的当前表不是最终表。将添加更多列。所以我需要一个解决方案,它可以适用于具有 2 列的表格或具有 5 列的表格,这与列的宽度无关,如果每列可以在向下滚动时保持相同的宽度而没有任何问题,那么这可以很棒。

Thanks

谢谢

回答by Kunal Gupta

It can also be done by keeping table header on a div{overflow:none} and table body on another div. You can keep header table in sync with content table horizontally on scroll event. Use table-layout: fixed so that applied column width remain same. One more thing adjust header table by giving an extra td at last to get accurate width as same as content table after getting a scroll bar on content table.

也可以通过将表头保留在 div{overflow:none} 上并将表体保留在另一个 div 上来完成。您可以在滚动事件上保持标题表与内容表水平同步。使用 table-layout: fixed 以便应用的列宽保持不变。另一件事是通过在内容表上获得滚动条后最后提供额外的 td 来调整标题表以获得与内容表相同的准确宽度。