如何使浮动标题列水平滚动并防止它们向左对齐

How can I make floating header columns to scroll horizontally and prevent them to align left?

本文关键字:左对齐 滚动 何使浮 标题 水平      更新时间:2023-09-26

我有一个html表,当用户滚动窗口时,它总是显示其标题列。它工作得很好,但标题(head)总是向左对齐;当表窄且居中时,列不再与标题列匹配。当表非常宽并且有许多列时,也会出现这种情况,迫使水平滚动显示;页眉不滚动,总是显示第一列。

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;
}

我该如何解决这个问题?

预览水平滚动问题

预览窄居中表-解决

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

添加:

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

(哦,我把你的很多jQuery链接在一起,只是因为我喜欢它的样子。)