当div转到位置时,滚动条会向下跳转:固定(但仅在使用滚动条时)

时间:2014-08-31 23:26:14

标签: javascript jquery html css

尝试制作一个简单的粘性导航栏,隐藏在向下滚动并在向上滚动时可见。当滚动滚轮时,它就像我想要的那样,但是当通过单击并拖动滚动条进行滚动时,当#avun-wrap从display: absolute转到display: fixed时,它会跳到底部。

知道发生了什么,可以做些什么?

Here's the JSFiddle.

HTML

<div id="nav-wrap">
    <div id="nav" class="clear">
        <nav>
            <h1>Navbar</h1>
            <ul>
                <li>item 1</li>
                <li>item 2</li>
            </ul>
        </nav>
    </div>
</div>

CSS

body {
    height: 1000px;
}
#nav {
    width: 100%;
    position: absolute;
    bottom: 0;
}
#nav-wrap {
    width: 100%;
    position: absolute;
    background-color: #e0e0e0;
}

JS

var previousScroll = 0,
    headerOrgOffset = $('#nav').height();
var nav = $('#nav-wrap');
var stickyNav = false;
var topPos = true;

nav.height($('#nav').height());

$(window).scroll(function () {
    var currentScroll = $(this).scrollTop();

    if (currentScroll > headerOrgOffset) {
        if (currentScroll > previousScroll) { // hvis skroller nedover
            if (topPos) {
                nav.css('position', 'fixed');
                nav.hide();
                topPos = false;
            } else {
                nav.slideUp();
                stickyNav = false;
            }
        } else if (currentScroll < previousScroll) { // hvis skroller oppover
            if (!topPos) {
                nav.slideDown();
                stickyNav = true;
            }
        }
    } else if (currentScroll == 0) {
        nav.css('position', 'absolute');
        topPos = true;
    }
    previousScroll = currentScroll;
});

0 个答案:

没有答案