Fixed header while scroll

前端 未结 2 1873
自闭症患者
自闭症患者 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:47

    Let me explain as to how this could be done.

    Steps

    1. Find your table header, and save its position
    2. Add a listener to the window's scroll event.
    3. Check the window scroll against your table header position
      1. If the position < window scroll - add a class to fix the table header
      2. Else, reset the css to behave like a normal header.

    I've posted a fiddle that you can find here.

    Code sample

    HTML

    ...
    // much more content
    My awsesome header number 1 My awsesome header number 2
    Content Content

    Javascript

    // Just so you get the idea behind the code
    
    var myHeader = $('#my_fixable_table_header');
    myHeader.data( 'position', myHeader.position() );
    $(window).scroll(function(){
        var hPos = myHeader.data('position'), scroll = getScroll();
        if ( hPos.top < scroll.top ){
            myHeader.addClass('fixed');
        }
        else {
            myHeader.removeClass('fixed');
        }
    });
    
    function getScroll () {
        var b = document.body;
        var e = document.documentElement;
        return {
            left: parseFloat( window.pageXOffset || b.scrollLeft || e.scrollLeft ),
            top: parseFloat( window.pageYOffset || b.scrollTop || e.scrollTop )
        };
    }
    

提交回复
热议问题