简体   繁体   English

滚动一定距离后的Bootstrap Navbar Fadeout

[英]Bootstrap Navbar Fadeout after Scrolling Certain Distance

Everything I've found so far on the net concerns fading on waypoint or x distance scrolled. 到目前为止我在网上发现的一切都与滚动的航点或x距离有关。

However, I need my navbar to fade out after moving a certain distance regardless of where the scroll begins on the page. 但是, 无论页面上滚动的位置如何 ,我都需要在移动一定距离后淡出导航栏。

So far, I've gotten it to fade in and out on scroll action alone. 到目前为止,我已经让它单独淡出滚动动作。 I've played with a few different methods stumbled upon here and on codepen where I've posted the code. 我在这里偶然发现了几种不同的方法,在我发布代码的代码中。 This seems the best method so far although it feels glitchy on mobile. 这似乎是迄今为止最好的方法,虽然它在移动设备上感觉很糟糕。 I've read somewhere this kind of code however shouldn't be used for mobile platforms. 我已经在某处读过这种代码,但不应该用于移动平台。

To be more objective here, I'd like the navbar to fadeOut when scrolling down a distance of 1/3 the screen REGARDLESS of starting point. 为了更加客观,我想在向下滚动屏幕1/3的距离时将导航栏淡出淡出。

Below is the JS code thanks to member Tushar. 以下是感谢成员Tushar的JS代码。

Full working code can be found here on codepen . 可以在codepen上找到完整的工作代码。

var lastScrollTop = 0, delta = 5;
    $(window).scroll(function(event){
       var st = $(this).scrollTop();

       if(Math.abs(lastScrollTop - st) <= delta)
          return;

       if (st > lastScrollTop){
           // downscroll code
           $(".navbar").fadeOut()
       } else {
          // upscroll code
          $(".navbar").fadeIn();

       }
       lastScrollTop = st;
    });

This is more of an update and the best "working" solution I was able to come up with so far. 这更像是一个更新和迄今为止我能够提出的最佳“工作”解决方案。

  • Using .stop() seems to remove some of the glitches on mobile platforms. 使用.stop()似乎可以消除移动平台上的一些故障。
  • I've added another if statement that forces the navbar to appear when x amount away from the top. 我添加了另一个if语句,强制导航栏在距离顶部x个数量时出现。 And when beyond that the old code takes over. 旧的代码接管了。

The problem so far is that I notice the fade only triggers when the scroll comes to a complete stop. 到目前为止的问题是我注意到只有在滚动完全停止时才会触发淡入淡出。 This ruins user experience. 这破坏了用户体验。 The above patches with increasing fade speed seem to make for a smoother experience on mobile. 上述具有增加的褪色速度的补丁似乎可以在移动设备上获得更流畅的体验。

var lastScrollTop = 0, delta = 5;
/*window.addEventListener("scroll", function()*/

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

  if(Math.abs(lastScrollTop - st) <= delta)
    return;

  if (st > lastScrollTop){
    // downscroll code
    $(".navbar").stop().fadeOut('fast')
  } else {
    // upscroll code
    $(".navbar").stop().fadeIn('fast');

  }if (window.scrollY < 500) {
        $('.navbar').stop().fadeIn('fast');
    }
  lastScrollTop = st;
});

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

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