Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - How to build simple sticky navigation at the page bottum?

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.

Sticky

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...