0

When scrolling down a page, I want to smoothly move the menu to the top of the page and change its position to sticky. With following code, I can make the menu fade in when scrolling.

How can I make it to smoothly move up and then stick there instead of suddenly fadein?

Here's my code:

jQuery:

$(function(){

    var menu = $('#menu'),
        pos = menu.offset();

        $(window).scroll(function(){
            if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){
                menu.fadeOut('fast', function(){
                    $(this).removeClass('default').addClass('fixed').fadeIn('fast');
                });
            } else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
                menu.fadeOut('fast', function(){
                    $(this).removeClass('fixed').addClass('default').fadeIn('fast');
                });
            }
        });

});

CSS:

.fixed {
    position: fixed;
    top: -5px;
    left: 0;
    width: 100%;
}

Demo: http://jsfiddle.net/ZzzxL/

4

1 回答 1

0

如果您从 jquery 函数中删除淡出,您应该实现您想要的:

$(window).scroll(function(){
    if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){
        menu.removeClass('default').addClass('fixed');
    } else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
        menu.removeClass('fixed').addClass('default');
    }
});

例子

于 2013-10-11T10:46:15.943 回答