简体   繁体   English

如何使这个Sticky Header jQuery标头起作用?

[英]How can I make this Sticky Header jQuery header work?

I am trying to get a sticky header to work like when I scroll down, the header will disappear and when I start to scroll up the header will reappear. 我试图使粘性标头正常工作,例如向下滚动时,标头将消失,而当我向上滚动时,标头将重新出现。

This is my jQuery: 这是我的jQuery:

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $(".header-top").outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $(".header-top").removeClass("sticky-header--top").addClass("sticky-header--hidden");
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $(".header-top").removeClass("sticky-header--hidden").addClass("sticky-header--fixed");
        }
    }

    lastScrollTop = st;
}

I am trying to make it add and remove classes from this div: 我正在尝试使其从此div中添加和删除类:

<div class="header__top sticky-header sticky-header--top" sticky-header="">

As you can see, I'm trying to get the div by selecting the class. 如您所见,我正在尝试通过选择类来获取div。 I've tried finding it with id but with no result. 我尝试用id查找它,但没有结果。

Thanks in advance! 提前致谢!

You are searching for $('.header-top') but your element has class header__top so use $('.header__top') 您正在搜索$('.header-top')但是您的元素具有header__top类,因此请使用$('.header__top')

Also, what is $(this) in your function? 另外,您的函数中的$(this)是什么? Maybe this should be $(window) or something else. 也许这应该是$(window)或其他名称。 Try and alert your variable after getting scrolltop to see if it actually has a value. 在获取scrolltop之后尝试警告您的变量,看看它是否确实具有值。

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

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