如何在用户向上/向下滚动时隐藏/显示导航栏 [英] How to hide/show nav bar when user scrolls up/down

查看:561
本文介绍了如何在用户向上/向下滚动时隐藏/显示导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户向上/向下滚动时隐藏/显示导航栏

Hide/show nav bar when user scrolls up/down

以下是我要实现的示例:
http://haraldurthorleifsson.com/

http://www.teehanlax.com/story/readability/

滚动时导航栏会从屏幕上滑出向下滚动并在屏幕上向下滑动。我已经想出了如何做淡入/淡出,但我想实现它与完全相同的动画,在示例中。

The navigation bar slides up off screen when you scroll down and slides back down on screen when you scroll up. I've figured out how to do it with fade in/fade out but I would like to achieve it with the exact same animation as in the example. Note: I already tried SlideIn() and like the way that it does the stretching animation...

JQUERY:注意:我已经尝试过SlideIn strong>

JQUERY:

var previousScroll = 0,
headerOrgOffset = $('#header').offset().top;

$('#header-wrap').height($('#header').height());

$(window).scroll(function() {
    var currentScroll = $(this).scrollTop();
    console.log(currentScroll + " and " + previousScroll + " and " + headerOrgOffset);
    if(currentScroll > headerOrgOffset) {
        if (currentScroll > previousScroll) {
            $('#header').fadeOut();
        } else {
            $('#header').fadeIn();
            $('#header').addClass('fixed');
        }
    } else {
         $('#header').removeClass('fixed');   
    }
    previousScroll = currentScroll;
});

CSS:

#header {
    width: 100%;
    z-index: 100;
}

.fixed {
    position: fixed;
    top: 0;
}

#header-wrap {
    position: relative;
}

HTML:

    <div id="header-wrap">
    <div id="header" class="clear">
        <nav>
            <h1>Prototype</h1>
        </nav>
    </div>
</div>


推荐答案

要使nav的内部内容向上滑动而不是逐渐隐藏,您需要对父元素执行动画,并将内部元素保留在父元素的底部,如下所示:

To get the inner content of the nav to slide up instead of being progressively hidden, you need to do the animation on the parent element, and keep the inner element at the bottom of the parent, like so:

jsfiddle

<div id="header-wrap">
    <div id="header" class="clear">
        <nav><h1>Prototype</h1>another line<br/>another line
        </nav>
    </div>
</div>

css

body {
    height: 1000px;
}

#header {
    width: 100%;
    position: absolute;
    bottom: 0;
}

#header-wrap {
    width: 100%;
    position: fixed;
    background-color: #e0e0e0;
}

js

var previousScroll = 0,
    headerOrgOffset = $('#header').height();

$('#header-wrap').height($('#header').height());

$(window).scroll(function () {
    var currentScroll = $(this).scrollTop();
    if (currentScroll > headerOrgOffset) {
        if (currentScroll > previousScroll) {
            $('#header-wrap').slideUp();
        } else {
            $('#header-wrap').slideDown();
        }
    } else {
            $('#header-wrap').slideDown();
    }
    previousScroll = currentScroll;
});

这篇关于如何在用户向上/向下滚动时隐藏/显示导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆