简体   繁体   中英

Sticking an element to the bottom of a fixed element on scroll?

Basically what I'm trying to achieve is to get a secondary navigation to stick to the bottom of the main navigation as soon as it meets the bottom of the main navigation on scroll. I'm still learning with jQuery and I've started to tear my hair out!

EDIT: Realised I didn't explain where I'd got to so far; the class is being added to the element however instead of fixing below the main header it's going off up out of the viewport.

EDIT 2: JSFiddle

If anyone could offer some help/advice I would appreciate it so much!

Outer-Header height: 160px

Markup is as follows:

HTML

<div class="outer-header" id="header">
    <header>
        ....    
    </header>        
</div>
<div id="page-wrap">
    <div class="upper-content">
        .....
    </div>
    <nav id="secondary_nav">
        ....
    </nav>

CSS

.sticky{
    position: fixed;
    top: 206px; /*top of viewport + height of secondary nav and outer-header*/
}

JS

var stickyNavTop = $('#secondary_nav').offset().top - 160;  

var stickyNav = function(){  
    var scrollTop = $(window).scrollTop();  

    if (scrollTop > stickyNavTop) {   
        $('#secondary_nav').addClass('sticky');  
    } else {  
        $('#secondary_nav').removeClass('sticky');   
    }  
};  

stickyNav();  

$(window).scroll(function() {  
    stickyNav();  
});  

This should work:

.sticky{
    position: fixed !important;
    top: 160px;
}

Your code is 99% there. You just need to specify the class better to stop it being overwritten.

DEMO http://jsfiddle.net/H9Bz3/27/

#secondary_nav.sticky{
    position: fixed;
    top: 160px;
}

Updated:

To ensure the height from the top is correct I would assign it CSS based on the element height of outter-header

DEMO http://jsfiddle.net/H9Bz3/28/

jQuery(document).ready(function($){
    //Sticky
    var stickyNavTop = $('#secondary_nav').offset().top - 160; 
    var topHeight = $('.outer-header').outerHeight();

    var stickyNav = function(){  
        var scrollTop = $(window).scrollTop();  

        if (scrollTop >= stickyNavTop) {   
            $('#secondary_nav').css({
                'position': 'fixed',
                'top': topHeight+'px'
            });  
        } else {  
            $('#secondary_nav').css({
                'position': 'relative',
                'top': '0'
            });  
        }  
    };  

    stickyNav();  

    $(window).scroll(function() {  
        stickyNav();  
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM