简体   繁体   中英

Sticky Header / Javascript

Good morning I am working on a sticky header for my site, I've got it working but it seems to snap into place, I want to be smooth! how do I go about this?

My site: http://www.trevorpeters.co.uk/tpwebdesign

CSS:

.sticky {  
    position: fixed;  
    width: 100%;  
    left: 0;  
    top: 0;  
    z-index: 100;  
    border-top: 0;  
}

JS

$(document).ready(function() {  
var stickyNavTop = $('.nav').offset().top;  

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

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

stickyNav();  

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

By default the header is in your document flow, 'pushing' the rest of the content down. If you make it sticky, it doesn't push the rest of the document down making it snap upwards. You can fix this by making your banner sticky from the start and giving your content a top margin equal to the height of your header. This way you can just get rid of the javascript all together.

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