2015-05-15 158 views
2

我正在为网站创建导航菜单。当用户滚动过点497px时,它需要改变颜色。我已经写了这个剧本:JQuery偏移脚本

$(document).ready(function(){ 

    function checkOffset() { 
     var offset = $(document).scrollTop(); 
     console.log(offset); 
     if(offset > 497){ 
      $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000); 
      $("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
     }else{ 
      $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000); 
      $("nav a").animate({color: '#1B1B1B'}, 1000); 

     } 
     } 
    $(window).scroll(function() { 
     checkOffset(); 
    }); 

    }); 

如果我刷新页面,这是过去的那个点,然后它确实改变了,但是如果我只是滚过这一点,然后它不会改变。我怎样才能解决这个问题?

+0

您的脚本可能有效。但是因为你在每张卷轴上制作动画。有连续动画周期的机会。我的建议是先暂时将'animate'改为'css'方法,看看它是否有效。如果确实如此,请确保在动画之前调用'stop()',请参阅URL https://api.jquery.com/stop/ –

+0

是的。 – Jon

+0

然后,让我添加这个答案。让这对其他人也有用。 –

回答

1

您的脚本可能有效。

但是因为您在每张卷轴上都有动画。有连续动画周期的机会。

可能的解决方案将是(这些点中的任何一个),

  1. 要使用任意css方法,而不是animate
  2. 动画应该帮助之前执行stop()
  3. 执行animate方法

要知道在jQuery的更多stop()前检查现有的颜色值。

0

你应该调用checkOffset();多一次:

$(document).ready(function(){ 

    function checkOffset() { 
     var offset = $(document).scrollTop(); 
     console.log(offset); 
     if(offset > 497){ 
      $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000); 
      $("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
     } else { 
      $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000); 
      $("nav a").animate({color: '#1B1B1B'}, 1000); 
     } 
    } 
    $(window).scroll(function() { 
     checkOffset(); 
    }); 

    checkOffset(); // <-- HERE 

}); 
+0

是什么原因? – kosmos

1

要使用带颜色的.animate(),您需要使用jQueryUI。因此,该框架添加到您的头上:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js""></script> 

然后再试一次(我修改了一点当前的代码):

$(function(){ 
    $(window).on('scroll', function() { 
     checkOffset(); 
    }); 
}); 

function checkOffset() { 
    var $target = $('#fixedBar'); 
    var offset = $(window).scrollTop(); 
    console.log(offset); 
    if(offset >= 10){ 
     $target.stop(true, false).animate({ 'background-color': 'green'}, 1000); 
     //$("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
    } 
    else if(offset < 10){ 
     $target.stop(true, false).animate({ 'background-color': 'blue' }, 1000); 
     //$("nav a").animate({color: '#1B1B1B'}, 1000); 
    } 
} 

Check the jsFiddle