首页 > 解决方案 > 使粘性表格标题随水平滚动移动

问题描述

我有一个具有“粘性”标题的 HTML 表格,即表格垂直滚动时,标题保持在原来的位置。

问题是我需要它与水平滚动一起移动,而不是垂直滚动。

CSS

    .sticky {
        position: fixed;
        top: 50px;
    }

JS

    window.onscroll = function () { stickyFunction() };

    var header = document.getElementById("theader");
    var sticky = header.offsetTop;

    function stickyFunction() {
        if (window.pageYOffset > sticky) {
            header.classList.add("sticky");
            $("theader").css("left", window.pageXOffset); //this is what I'm trying to make it move with horizontal scroll
            $("theader").css("margin-left", window.pageXOffset); //didn't work either
        } else {
            header.classList.remove("sticky");
        }
    }

标签: htmljquerycss

解决方案


这是任何好奇的人的解决方案:

    .sticky {
        position: absolute;
    }
    <div id="theader">
            <table id="headertable" border="0" class="corrTable">
    etc...
    window.onscroll = function () { stickyFunction() };

    var header = document.getElementById("theader");
    var sticky = header.offsetTop;

    function stickyFunction() {
        if (window.pageYOffset > sticky) {
            header.classList.add("sticky");
            $("#theader").css({ "top": ($(window).scrollTop() + 50) + "px" });
        } else {
            header.classList.remove("sticky");
        }
    }

推荐阅读