简体   繁体   中英

Header to reappear when user scrolls up by value (100px)

So I am using the following script to hide my header when the user scrolls down, and it only changes the CSS when the page is 200px from the top and scrolled down.

I am simply trying to have the class navbar applied when the user scrolls up & 100 from the bottom as well as when scrolled down and 200 from the top. 200 from the top is applied. I have prevented the header being hidden when at the top of the page, I also want to prevent it being shown when at the bottom until scrolled up 100px

HTML Header :

 <header> 
   <nav> 
   </nav> 
 </header

Script:

<script>
(function($) {
  var ost = 0;
   $(window).scroll(function() {
    var cOst = $(this).scrollTop();

 if(cOst > 200 && cOst > ost) {
   $('nav').addClass('fixed').removeClass('navbar');
}
else {
   $('nav').addClass('navbar').removeClass('fixed');
}

ost = cOst;
});
})(jQuery);
</script>

CSS:

 .navbar {
  top: 0;
  z-index: 9999;  }

.fixed {
 top: -62px;}

nav {
margin:0;
padding:0px;
text-align:center;
background-color: #ffffff;
border-bottom: 2px solid #d5dbdb;
width: 100%;
height: 60px;
position: fixed;
z-index: 9999;
top:0;
left: 0;
opacity: 0.9;
transition: all 200ms linear;
-moz-transition: all 200ms linear;
-webkit-transition: all 200ms linear;    }

Any feedback, comments or help is greatly appreciated.

Thanks (Y)

Basically what you want to do is keep another variable for total so you can count how far up the user scrolled and reset it to 0 when they scroll back down. Because of how the script was written though if the header was shown by scrolling up any scrolling down at all would hide it again, so I made a second total variable and named them upTotal & downTotal . You can change the amount scrolled up/down needed to show/hide the header by changing the values (upTotal >= 100) & (downTotal >= 200) respectively. Please let me know if this is not what you had in mind.

(function ($) {
    var ost = 0,
        upTotal = 0,
        downTotal = 0;
    $(window).scroll(function () {
        var cOst = $(this).scrollTop();

        if (cOst > ost) {
            upTotal = 0;
            downTotal += (cOst - ost);
            if (downTotal >= 200) {
                $('nav').addClass('navbar').removeClass('fixed');
            }
        } else {
            downTotal = 0;
            upTotal += (ost - cOst);
            if (upTotal >= 100) {
                $('nav').addClass('fixed').removeClass('navbar');
            }
        }
        ost = cOst;
    });
})(jQuery);

Here is a very crude, but working jsFiddle DEMO .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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