简体   繁体   中英

.bind('scroll'), add animation or reduce “bounce”

This is a jQuery script I'm using to have the menu fixed when users scroll the page. This is a live demo.

<script>
var num = 170; //number of pixels before modifying styles

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > num) {
        $('#header').addClass('fixed');
    } else {
        $('#header').removeClass('fixed');
    }
});
</script>

<style>
.fixed {
    position:fixed;
    top:0;
    background-color:#e4e4e4;
    width:100% !important;
    background-image: url("images/logo_small.png") !important;
    background-size:20px auto !important;
    margin:0 auto !important;
    padding:20px 0 10px !important;
    background-position:90px center !important;
    z-index:1;
}


#header {
    background-image: url("images/logo.png");
    background-position: 30px 5px;
    background-repeat: no-repeat;
    background-size: 152px auto;
    font-size: 13px;
    margin: 18px auto 0;
    padding: 60px 0 87px 100px;
    width: 780px;
}
</style>

Problem is, as you can see, when "small" menu appears there's a "jump", and the content goes up abruptly.

http://jsfiddle.net/andaywells/jVy5L/64/embedded/result/

var num = 170; //number of pixels before modifying styles

$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {

    $('#header').addClass('fixed');


} else {
    $('#header').removeClass('fixed');

}
});

I removed the fadeout, and added position: fixed; to the header, so using css transitions, the scroll is much more fluid.

Check this url relative sidebar to fixed, when it reaches the end of window

  $(function() {      
    $(window).scroll(function(evt) {
        var top = $('#header').offset().top;
        var sidebartop = $('#header').height() / 2;
        var y = $(this).scrollTop() - sidebartop;
        if (y > top) {
                $('#header').addClass('fixed').css( "top",  -top -sidebartop + 220)
            }
        else {
            $('#header').removeClass('fixed');
            $('#header').css( "top", "auto" );
        }
    });
});

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