Javascript表头不粘

时间:2018-12-23 17:22:30

标签: javascript html

我试图根据W3Schools上的解决方案实现一个粘性表头: https://www.w3schools.com/howto/howto_js_sticky_header.asp

但是,我的表标题仍然不响应滚动到标题上方而停留。控制台日志给出了stickywindow.pageYOffsetheader.offsetHeight的期望值。 我想念什么吗?

我的代码摘要如下:

<html lang="en">
    <head>
        <style type="text/css">
        /*...*/
                #myTable {
                    float:left;
                    width:75%;
                    background-color:#fff;
                    padding:6px;
                    margin-left:175px;
                }

                #myTable th {
                    cursor:pointer;
                    position: sticky;
                    top: 0;
                }

                #myTable th:hover {
                    background-color:#66991c;
                    color:white;
                }

                #myTable tr:nth-child(even) {
                    background-color:#eee;
                }

                #myTable tr:nth-child(odd) {
                    background-color:#fff;
                }

                #table-link {
                    display:block;
                    text-decoration:none;
                    background-color:black;
                    color:white;
                    border-radius:5px;
                }

                #table-link a {
                    display:block;
                    text-decoration:none;
                    background-color:black;
                    color:white;
                    border-radius:5px;
                }

                #table-link a:hover {
                    display:block;
                    text-decoration:none;
                    background-color:#66991c;
                    color:white;
                    border-radius:5px;
                }

                .sticky {
                    position: fixed;
                    top: 0;
                    width: 100%;
                }
        /*...*/
        </style>    
    </head>
    <body>
        ...
        <table id="myTable">
        <div id="myHeader">
            <caption>...</caption>
            <thead>...</thead>
        </div>
        <tbody>...</tbody>
        </table>
        ...

        <script>
        window.onscroll = function() {myFunction()};

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

        function myFunction() {
          if (window.pageYOffset > sticky) {
            header.style.paddingTop = header.offsetHeight + 'px';
            header.classList.add("sticky");
          } else {
            header.style.paddingTop = 0;
            header.classList.remove("sticky");
          }
        }
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:5)

在不使用Java脚本的情况下使用position:sticky

.sticky {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
}