如何使固定表标题与tbody数据水平滚动? [英] How to make fixed table header scroll horizontally in sync with tbody data?

查看:69
本文介绍了如何使固定表标题与tbody数据水平滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有固定标题的下表.我希望标题可以与数据水平滚动吗?因此,当用户水平滚动tbody数据时,标题也将水平滚动.可以这样做吗?

I have the following table with a fixed header. I want the header to be scrollable horizontally insync with the data? so that the header also scrolls horizontally when the user scrolls the tbody data horizontally. Is it possible to do that?

注意:我将动态创建表的列和标题.因此,有时我只能有2列,有时是10列和10个标题

Note: I will be creating the table columns and header dynamically.. so sometime i can only have 2 columns sometimes 10 columns with 10 headers

小提琴代码

<table border="1">
    <thead>
        <tr>
            <th>head1</th>
            <th>head2</th>
            <th>head3</th>
            <th>head4</th>
              <th>head4</th>
        </tr>
    </thead>
    <tbody>
        <tr>

            <td>row 1, cell 1</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
        <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
         <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
              <td>row 1, cell 2</td>
        </tr>
         <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
    </tbody>
</table>

table tbody
{
    display: block;
}
table thead
{
    display: block;
    overflow:auto;
}

table tbody 
{
   overflow: auto;
   height: 100px;
   position:absolute;
}

th
{
    width: 72px;
}

推荐答案

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

The only way to sync them is to listen to the scroll event, and update the header position accordingly. Something like this (assuming window is the container):

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).

Note: You can even update the position by the transform property with translate/translate3d if you'd like to as well (instead of marginLeft).

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

If your container is not window, you will have to rely on the DOMElement.scrollLeft property. Happy coding!

这篇关于如何使固定表标题与tbody数据水平滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆