简体   繁体   中英

div position fixed on the scroll, start before the top of the page

How can I get the "Sidebar" to be fixed position when it reaches the "Fixed header" and not the page's top?

jsfiddle

$(function() {
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0));

    var maxY = footTop - $('#sidebar').outerHeight();

    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        if (y > top) {
            if (y < maxY) {
                $('#sidebar').addClass('fixed').removeAttr('style');
            } else {
                $('#sidebar').removeClass('fixed').css({
                    position: 'absolute',
                    top: (maxY - top) + 'px'
                });
            }
        } else {
            $('#sidebar').removeClass('fixed');
        }
    });
});

This line:

if (y > top) {

assuming your fixed header has no padding (otherwise you'll have to take that into account as well) you could change to this

if (y >= top - $('#fixedHeader').height()) {

remove top:0px; from your sidebar css, and add the expected height for for your fixed header (currently you've given it a height of 40px), so

#sidebar.fixed {
  position: fixed;
  top: 40px;
}

I've also removed padding from your #fixedHeader , as you didn't specify what it was/if you even wanted any. If you did want padding, as mentioned above, you'll have to add that into your calculation as well.

http://jsfiddle.net/VtPcm/706/

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