【问题标题】:How can I make floating header columns to scroll horizontally and prevent them to align left?如何使浮动标题列水平滚动并防止它们左对齐?
【发布时间】:2018-09-16 03:37:17
【问题描述】:

当用户滚动窗口时,我有一个始终显示其标题列的 html 表。它工作正常,但标题(头)总是左对齐;当表格变窄且居中时,列不再匹配标题列。当表格很宽并且有很多列时也会发生这种情况,从而迫使水平滚动出现;标题不滚动,总是显示第一列。

JavaScript:

function moveScroll(){
var scroll = $(window).scrollTop();
var anchor_top = $("#main_table").offset().top;
var anchor_bottom = $("#bottom_anchor").offset().top;
if (scroll > anchor_top && scroll < anchor_bottom)
{
    clone_table = $("#clone");
    if(clone_table.length == 0)
    {
        clone_table = $("#main_table").clone();
        clone_table.attr('id', 'clone');
        clone_table.css({position:'fixed', 'pointer-events': 'none', top: 0});
        clone_table.width($("#main_table").width());
        $("#table_container").append(clone_table);
        $("#clone").css({visibility:'hidden'});
        $("#clone thead").css({visibility:'visible'});
    }
}
else
{
    $("#clone").remove();
}
}
$("#main_table").wrap('<div id="table_container"></div>');
$('<div id="bottom_anchor"></div>').insertAfter('#main_table');
$(window).scroll(moveScroll);

HTML:

<table id="main_table" align="center">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tr>
        <td>Column</td>
        <td>Column</td>
        <td>Column</td>
        <td>Column</td>
    </tr>
    <tr>
        <td>Column</td>
        <td>Column</td>
        <td>Column</td>
        <td>Column</td>
    </tr>
</table>

CSS:

body {
    width: 500px;
}
thead tr {
    background-color: lightgrey;
}

我该如何解决这个问题?

预览horizontal scroll problem

预览narrow centered table - 已解决

【问题讨论】:

    标签: javascript jquery html-table


    【解决方案1】:

    http://jsfiddle.net/AvaUU/7/

    添加:

    .css({
        position: 'fixed',
        'pointer-events': 'none',
        left: $("#main_table").offset().left+'px',
        top: 0
    })
    

    (哦,我将你的很多 jQuery 链接在一起,只是因为我喜欢它的外观。)

    【讨论】:

    • 谢谢!这解决了居中表格问题。但不是水平滚动的一个宽度。你能检查一下吗?我不是 jQuery 专家。 link
    • 谢谢。它解决了水平滚动问题,但打破了居中表格的问题。我会尝试找到解决方案。还是谢谢!
    • 是否也可以让第一列表现得像这样?这样第一行(列标题)和第一列应该始终可见?谢谢....
    • 有可能;我以前从不担心它,因为有插件可以帮你做——datatables.net/release-datatables/examples/basic_init/… 是最受欢迎的。
    • 我已经做到了。 http://jsfiddle.net/AvaUU/35/。我在您的建议中只发现了类似 iframe 的解决方案(带有额外的滚动条)。奇怪的是那种固定列随处可见,而我需要的似乎很难找到。
    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多