jquery - 表格标题和可滚动表格无法完美呈现

标签 jquery css

我有 2 个不同的表,一个用于标题数据,另一个用于可滚动的正文。

<div class="form-horizontal" style="margin-top:15px;">
    <table id="header">
        <thead>
            <tr>
                <th></th>
                ...8x
            </tr>
        </thead>
    </table>
    <div id="table-container" style="overflow-y:auto; max-height:150px;">
    <table class="table" id="table">
        <tbody>
                <tr>
                    <td ></td>
                    ...8x
                </tr>
        </tbody>
    </table>
    </div>
</div>

现在我想用 JQuery 设置表格的宽度。

$('#table td:nth-child(1)').width('8%');
$('#table td:nth-child(2)').width('8%');
$('#table td:nth-child(3)').width('8%');
$('#table td:nth-child(4)').width('0%');
$('#table td:nth-child(5)').width('8%');
$('#table td:nth-child(6)').width('8%');
$('#table td:nth-child(7)').width('23%');
$('#table td:nth-child(8)').width('23%');
$('#header th:nth-child(1)').width('8%');
$('#header th:nth-child(2)').width('8%');
$('#header th:nth-child(3)').width('8%');
$('#header th:nth-child(4)').width('0%');
$('#header th:nth-child(5)').width('8%');
$('#header th:nth-child(6)').width('8%');
$('#header th:nth-child(7)').width('23%');
$('#header th:nth-child(8)').width('23%');

启动元素时,标题呈现为(示例第一列):

<th style="width: 10%;"></th>

(预期宽度:8%)

正文呈现为(示例第一列):

<td style="width: 16%;"></td>

(预期宽度:8%)

所以布局不匹配。为什么渲染输出与预期不同?

(关闭问题,我通过使用 JQuery 将 td 设置为与 th 相同的宽度来修复问题:

var ths = $('#header').children('thead').children('tr').children('th').length;
    for (counter = ths; counter >= 0; counter--) {
        var headerwidht = $('#header th:nth-child(' + counter + ')').width();
        $('#table td:nth-child(' + counter + ')').width(headerwidht + 'px');
    }

但我仍然很好奇为什么表格会意外呈现。 )

最佳答案

你的两个表都有 css“table-layout: fixed”吗? 当您使用百分比为表格的 td/th 设置宽度时,您应该拥有它。

顺便说一句,由于总宽度百分比的总和不需要等于 100%,您应该使用 JS 来切换表格的类,而不更改它们的宽度。在类的基础上,您可以使用 CSS 来显示/隐藏您想要的列,甚至可以根据需要更改保留列的宽度。

希望对您有所帮助。

关于jquery - 表格标题和可滚动表格无法完美呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202773/

相关文章:

javascript - 谷歌图表设计在切换到另一个标签时令人不安

html - 无法获得扩展整个页面的两个背景图像?

javascript - 识别侧边栏何时处于事件状态

javascript - 如何在可以更改的值上触发函数?

javascript - 为什么我的 Leaflet 弹出窗口意外关闭?

javascript - 我认为我的 jquery 函数不正确

javascript - 滚动条和平滑滚动代码

css - iOS 深灰框事件样式

jquery - jQuery 影响不同元素后禁用 Css 悬停效果

javascript - 使用 jQuery 将表单中的变量作为街景 API 参数传递的问题