淡入/淡出导航栏 [英] Fade in/Fade out navigation bar

查看:91
本文介绍了淡入/淡出导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的导航栏设置为保持固定并在我向下滚动时淡入0.8不透明度,并在我向上滚动时返回到其正常位置和不透明度。

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.

我的jquery代码是:

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);

        }
    });
});

我的css代码是:

.fixed {

    position:fixed;

    top:0;
}

当我向下滚动但当我没有回到原来的不透明度时,它会淡出向上滚动。我是jQuery的新手。

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

推荐答案

我认为问题是你要设置<$ c每次触发滚动事件时,$ c> fadeTo 函数。因此,当您向下滚动时,您将向动画效果队列添加许多淡出调用。向后滚动时,所有淡出效果(每个效果需要1.5秒)必须在第一次淡入调用发生之前完成。

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.

您可以通过添加对jQuery的 .stop(true)的调用来解决此问题,以便每个滚动事件都清除动画队列:

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>

请注意,这意味着在用户停止滚动之前不会发生 fadeTo 动画。

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

这篇关于淡入/淡出导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆