Fade in/Fade out navigation bar

心已入冬 提交于 2019-12-23 12:08:52

问题


I'm trying to set my navigation bar to remain fixed and fade to 0.8 opacity when i scroll down and return to his normal position and opacity when i scroll back up.

my jquery code is :

jQuery(document).ready(function(){

    var navOffset = jQuery("nav").offset().top;

    jQuery(window).scroll(function(){

        var scrollPos = jQuery(window).scrollTop();

        if(scrollPos > navOffset) {
            jQuery("nav").addClass("fixed");
            jQuery("nav").fadeTo(1500,0.5);
        } else {
            jQuery("nav").removeClass("fixed");
            jQuery("nav").fadeTo(1500,1);

        }
    });
});

and my css code is :

.fixed {

    position:fixed;

    top:0;
}

It fades out when i scroll down but doesnt return to his original opacity when i scroll back up.I'm new to jQuery.


回答1:


I think the problem is that you're setting the fadeTo function on every firing of the scroll event. Thus, when you scroll down, you're adding many "fade out" calls to the animation effects queue. When you scroll back up, all of the "fade out" effects (each of which takes 1.5 seconds) have to finish before the first "fade in" call takes place.

You can fix this by adding a call to jQuery's .stop(true) so that each scroll event clears the animation queue:

jQuery(document).ready(function() {

  var navOffset = jQuery("nav").offset().top;

  jQuery(window).scroll(function() {

    var scrollPos = jQuery(window).scrollTop();
    jQuery("nav").stop(true);

    if (scrollPos > navOffset) {
      jQuery("nav").addClass("fixed");
      jQuery("nav").fadeTo(1500, 0.5);

    } else {
      jQuery("nav").removeClass("fixed");
      jQuery("nav").fadeTo(1500, 1.0);
    }
  });
});
body {
  height: 4096px;
  padding-top: 32px;
}
nav {
  height: 128px;
  width: 100%;
  border: 1px solid black;
  background-color: #00aa00;
}
.fixed {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>so</title>
  <meta charset="UTF-8">

</head>

<body>

  <nav></nav>

</body>

</html>

Note that this means the fadeTo animation won't take place until the user stops scrolling.




回答2:


It's there another solution to do that? Because when i scroll back up the time that it takes for the "fadeTo" action is verry delayed(~4 secconds) i dont think that's normal.



来源:https://stackoverflow.com/questions/31748265/fade-in-fade-out-navigation-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!