Fixed header while scroll

前端 未结 2 1871
自闭症患者
自闭症患者 2021-02-11 08:29

I have the header of a table in the middle of a page, but since the page is huge, I want to fix the header to the top of browser while I scroll down for the page...

So

2条回答
  •  盖世英雄少女心
    2021-02-11 08:50

    You're looking for a horizontally oriented "sticky box" that follows you down the page as you scroll.

    Here is a walkthrough that explains how to create this effect for a sidebar: http://css-tricks.com/scrollfollow-sidebar/

    I modified the code to work with a generic example that spans the width of the page:

    HTML:

    HEAD
    Table Header
    Content

    CSS:

    .wrapper {
      border:1px solid red;
    }
    .head{
      height: 100px;
      background: gray;
    }
    .header {
      background:red;
      height:100px;
      left:0;
      right:0;
      top:0px;
      margin-top:100px;
      position:absolute;
    }
    
    .content {
       background:green;
       height:1000px;
    }
    
    .footer {
       background:blue;
       height:100px;
    }
    

    jQuery:

    $(function() {
    
        var $sidebar = $(".header"),
            $window = $(window),
            offset = $sidebar.offset(),
            topPadding = 0;
    
        $window.scroll(function() {
            if ($window.scrollTop() > offset.top) {
                $sidebar.stop().animate({
                    top: $window.scrollTop() - offset.top + topPadding
                });
            } else {
                $sidebar.stop().animate({
                    top: 0
                });
            }
        });
    
    });​
    

    ​This will animate the header block into view when you scroll beyond where it originally appears.

    jsFiddle here

提交回复
热议问题