简体   繁体   English

如何查找表的列宽并应用于同一页面中的另一个表

[英]how to find table column width and apply to another table in the same page

I'm using 2 tables to create a scroll-able table. 我正在使用2个表来创建可滚动表。 But they are 2 separated tables and the column width do not match. 但是它们是2个分离的表,列宽不匹配。 How to get the column width from tbody and apply it to thead? 如何从tbody获取列宽并将其应用于thead?

<div>
    <table id="header">
        <thead>
            <tr>
                <td>header 1</td>
                <td>header 2</td>
                <td>header 3</td>
                <td>header 4</td>
            </tr>
        </thead>
    </table>
</div>
<div class="scrollable">
    <table id="body">
        <tbody>
            <tr>
                <td>data 1-1</td>
                <td>1-2</td>
                <td>data 1-3</td>
                <td>data 1-4</td>
            </tr>
            <tr>
                <td>data 2-1</td>
                <td>2-2</td>
                <td>data 2-3</td>
                <td>data 2-4</td>
            </tr>
            <tr>
                <td>data 3-1</td>
                <td>3-2</td>
                <td>length testing</td>
                <td>data 3-4</td>
            </tr>
            <tr>
                <td>data 4-1</td>
                <td>short</td>
                <td>data 4-3</td>
                <td>data 4-4</td>
            </tr>
        </tbody>
    </table>
</div>

jsfiddle 的jsfiddle

Thank you in advance. 先感谢您。

This should give you what you are looking for. 这应该给您您想要的东西。 The table width also has to be matched up. 桌子的宽度也必须匹配。

//match the table width
$("#header").width($("#body").width());

var bodyTr = $("#body tr:first td");
$("#header tr:first td").each(function(index, value) {
    $(this).width(bodyTr.eq(index).width());
});

Here is your modified fiddle: https://jsfiddle.net/3L17sgjw/4/ 这是您修改过的小提琴: https : //jsfiddle.net/3L17sgjw/4/

You can set a class for every column with something like this: 您可以为每个列设置一个类,如下所示:

$("#header td:nth-of-type(1)").addClass("column1");
$("#body td:nth-of-type(1)").addClass("column1");
//And so with every column you want

And then set the fixed width value for that class. 然后为该类设置固定的宽度值。 The correct way of doing this would be with a for loop to do not duplicate the same two lines for every column. 正确的方法是使用for循环,不要为每一列重复相同的两行。

But i think that it would be easier if you just add your 'scrollable' class to the tbody without keeping thead and tbody separated in different divs. 但是我认为,如果仅将“ scrollable”类添加到tbody中,而不必将thead和tbody分开放在不同的div中,则会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM