How to build simple sticky navigation at the page

2020-02-07 04:36发布

问题:

I'm trying to make it so when you load a page a div is sticking to the bottom of it. Then when a user scrolls down it sticks to the top.

I can do the stick to the top part using a sticky element.

<div id="container">
<div id="menu">
    <ul>
        <li><a href='#test'>Line 1</a></li>
        <li><a href='#'>Line 2</a></li>
        <li><a href='#'>Line 3</a></li>
    </ul>
</div>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $(window).scroll(function(){
           if($(this).scrollTop()>=660)
           {
           $('#menu').addClass('fixed');
           }else{
               $('#menu').removeClass('fixed');
           }
                   });
    });
    </script>

I just can't do it so it sticks to the bottom on load. I've attached a little mockup if it's unclear.

回答1:

UPDATED.
Here is working jsFiddle to examine.

jQuery:

$(document).ready(function() {
    var windowH = $(window).height();
    var stickToBot = windowH - $('#menu').outerHeight(true);
    //outherHeight(true) will calculate with borders, paddings and margins.
    $('#menu').css({'top': stickToBot + 'px'});

    $(window).scroll(function() {
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > stickToBot ) {
            $('#menu').css({'position':'fixed','top' :'0px'});
        } else {
            $('#menu').css({'position':'absolute','top': stickToBot +'px'});
        }
    });
});​

Note: if you want to go further, i suggest to inspect this answer too:

Setting CSS value limits of the window scrolling animation