如何使固定表头水平滚动与tbody数据同步?

我有下表带有固定标题。 我希望标题可以水平滚动与数据同步吗? 这样当用户水平滚动tbody数据时,标题也会水平滚动。 有可能吗?

注意:我将动态创建表列和标题..所以有时我只能有2列,有时10列,10个标题

小提琴代码

head1 head2 head3 head4 head4
row 1, cell 1 row 1, cell 2 row 1, cell 2 row 1, cell 2 row 1, cell 2
row 2, cell 1 row 2, cell 2 row 1, cell 2 row 1, cell 2 row 1, cell 2
row 2, cell 1 row 2, cell 2 row 1, cell 2 row 1, cell 2 row 1, cell 2
row 2, cell 1 row 2, cell 2 row 1, cell 2 row 1, cell 2 row 1, cell 2
table tbody { display: block; } table thead { display: block; overflow:auto; } table tbody { overflow: auto; height: 100px; position:absolute; } th { width: 72px; }

同步它们的唯一方法是收听scroll事件,并相应地更新标题位置。 像这样的东西(假设window是容器):

 var headerEl = document.getElementById('yourHeadElement'); // or w/e window.addEventListener('scroll', function(e){ var offset = window.pageXOffset; headerEl.style.marginLeft = (-offset) + 'px'; // alternatively: // headerEl.style.transform = 'translate3d('+ (-offset) +'px,0,0);'; }, false); 

注意:如果您愿意,您甚至可以使用translate / translate3d通过transform属性更新位置(而不是marginLeft)。

如果您的容器不是窗口,则必须依赖DOMElement.scrollLeft属性。 快乐的编码!