2013-02-21 104 views
0

在我的页面上,当用户说1000个像素向下滚动页面时,我的导航淡出,当我向后滚动导航淡入时,我使用以下完美的作品。 ..淡入淡出jQuery的问题

// Fade Navigation 

if(!$('nav ul').is(':visible')) { 
    $('nav ul').stop().fadeIn(500); 
} else { 
    $('nav ul').stop().fadeOut(500); 
} 

我唯一的问题是,如果你真的快速滚动,动画完全不认识如果它的可见或不可见,有没有办法阻止呢?

+0

什么浏览器?你可以让[jsfiddle](http://jsfiddle.net/)向我们展示吗? – Automatico 2013-02-21 16:49:39

+0

我不认为':visible'就是这样工作的---即使元素是从视图中滚动出来的,如果它们仍占用文档中的空间,它们就被认为是':visible'。另外,您可能很高兴知道有一个'.fadeToggle()'函数! – 2013-02-21 16:50:12

+0

jQuery完全知道你的元素是否可见。事情是,'.stop()''fadeOut'动画使元素部分可见,这被视为':visible'。 – 2013-02-21 16:52:15

回答

1

如果您在true传递的第二个参数.stop(),它会停止动画元素跳转至状态时,它应该是如果动画实际完成。

即如果调用$('nav ul').stop(true, true).fadeIn(500)而一个元素淡出,将停止淡出,使其之前跳转到它的逻辑结束(这是完全淡出)开始.fadeIn()动画。

利用这一点,你应该能够代替按照您的代码块的上方脱身:

$('nav ul').stop(true, true).fadeToggle(500); 

它会看起来有点生涩,虽然,但你可以解决它多一点复杂的逻辑。

0

我一直在玩这个。请参阅代码中的评论。

<nav class="main"> 
    <ul> 
     <li>One</li> 
     <li>Two</li> 
    </ul> 
</nav> 

<script type="text/javascript"> 

    // Do this outside of the onscroll handler. onscroll is fired a lot, 
    // so performance will slow if you're having to create jq instances 
    // or navigate the dom several times 
    var $wnd = $(window); 
    var $nav = $('nav.main'); 

    // Added this to block the main handler from executing 
    // while we are fading in or out...in attempt 
    // to smooth the animation 
    var blockHandler = false; 

    window.onscroll = function() { 
     if (!blockHandler) { 
      blockHandler = true; 

      // I've used 50 here, but calc the offset of your nav 
      // and add the height to it. Or, maybe just half the 
      // height to it so you can see the animation. 
      if ($wnd.scrollTop() < 50) { 
       $nav.fadeIn(500, function() { 
        blockHandler = false; 
       }); 
      } else { 
       $nav.fadeOut(500, function() { 
        blockHandler = false; 
       }); 
      } 
     } 
    }; 

</script> 
+0

对不起,我不认为冒犯你,但我认为利亚姆很难让他的菜单顺利淡入淡出,所以为什么我发布了一些“我一直在玩的东西”,这可能会给他有关如何实现他想要的新想法。 – 2013-02-21 17:48:49

+0

Sparky - 滚动代码窗口。 – 2013-02-21 17:55:24

+0

一般而言,答案会附带说明,尤其是在很多情况下,答案似乎无关紧要。这是jQuery,不需要测试浏览器......这就是使用它的要点。 – Sparky 2013-02-21 17:59:17