简体   繁体   English

如何根据滚动位置淡入和淡出导航栏

[英]How to fade in and fade out navbar based on scrolling position

I have a vertical navbar that I want to appear, and slowly fade in, when the user scrolls below the header. 我有一个垂直导航栏,当用户滚动到标题下方时,它会逐渐淡入。 Likewise, I want the navbar to disappear, and slowly fade out, if the user scrolls onto the header. 同样,如果用户滚动到标题上,我希望导航栏消失,然后逐渐淡出。 This is my current function: 这是我当前的功能:

    $(window).scroll(function() {
        var scrollPos = $(window).scrollTop();
        if (scrollPos < 650) {
            $('.navbar').fadeOut(4000);
        } else {
            $('.navbar').fadeIn(4000);
        }
    });

The issue with this is that when I scroll below the header (or specifically a position of 650), the navbar quickly appears at full opacity, slowly fades out, then slowly fades back in. When I scroll onto the header, it just quickly disappears. 这样做的问题是,当我滚动到页眉下方(或特定于650的位置)时,导航栏会以完全不透明的状态快速出现,然后慢慢淡出,然后再慢慢淡入。当我滚动到页眉时,它会迅速消失。 How do I fix this to get the desired behavior? 如何解决此问题以获得所需的行为?

Changed it to use css transition and also added a slight debounce for the scroll event. 将其更改为使用CSS过渡,并且还为滚动事件添加了轻微的反跳。 Stone the markup from @Adriani6 's fiddle, :P 从@ Adriani6的小提琴中删除标记:P

 (function(){ var timeout; var $window = $(window); var $navbar = $('.navbar'); $window.on('scroll', function(e){ clearTimeout(timeout); timeout = setTimeout(function(){ if ($window.scrollTop() < 650) { $navbar.removeClass('hide'); } else { $navbar.addClass('hide'); } }, 100); }); }()); 
 body{ height: 12000px; } .navbar{ height: 100px; width: 800px; background-color: green; position: fixed; transition: opacity 4s; opacity: 1; } .navbar.hide { opacity: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='navbar'></div> 

You should make sure to have .navbar hidden by default, giving it this CSS 您应该确保默认情况下隐藏.navbar ,并为其提供此CSS

.navbar {
  display: none;
}

Then it should fade in upon reaching that scroll position without that flash. 然后,它应在到达该滚动位置时淡出而没有该闪光灯。

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

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