简体   繁体   English

滚动后将导航栏返回到原始位置

[英]Return Navbar to Original Position After Scrolling

I have set up this page so that when you scroll past the top of the navbar, it becomes sticky and stays at the top of the page. 我已设置此页面,以便当您滚动到导航栏的顶部时,它会变得粘滞并停留在页面顶部。

I want it to return to its original position when you scroll back to the top of the page. 当您滚动回到页面顶部时,我希望它返回到其原始位置。

Here is a CodePen for the work I have right now. 这是我目前拥有的工作的CodePen How should I change the jQuery so it sticks back in its original position? 我应该如何更改jQuery,使其重新回到原来的位置?

$(window).on('scroll', function () {

    var $header = $("#header"),
        scrollTop = $(window).scrollTop(),
        elementOffset = $header.offset().top,
        distance = (elementOffset - scrollTop);

    if (distance < 0) {
        $header.css({
            "position": "fixed",
            "top": "0px",
            "left": "0",
            "right": "0"
        });
    }
});

Right now, this is how I change the header element into a fixed one as the user scrolls down the page. 现在,这就是当用户向下滚动页面时将标题元素更改为固定元素的方式。

Think of the solution in another way: 用另一种方式考虑解决方案:

CSS 的CSS

.affix {
    position:fixed;
    top:0;
    left:0;
    right:0;
}

JS JS

if (distance < 0) {
    $header.addClass("affix");
} else {
    $header.removeClass("affix");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM