滚动函数jquery

时间:2010-05-27 12:47:17

标签: jquery scroll opacity

我有一个固定的标题。 当我向上滚动时我想改变不透明度并在我向上滚动时恢复不透明度(在页面顶部) 我写下这个简单的脚本:

$(window).scroll(function () {  

   if(scrollY == 0){

   $("#header").animate({
   opacity: 1
   }, 1000);

   }

   if(scrollY > 0){

   $("#header").animate({
   opacity: 0.5
   }, 1000);   

   }

 });

实际上当我向下滚动时标题采用不透明度但是当我向上滚动页面顶部时他永远不会回到不透明度:1。 为什么呢?

1 个答案:

答案 0 :(得分:2)

这可能是一个更好的方法。它会在将不透明度设置为#header之前检查.5是否已设置动画。

此外,它将#header缓存在scroll处理程序之外的变量中。更好的表现。

var $header = $('#header');

$(window).scroll(function () {

   if(scrollY <= 0){
       $header.animate({
            opacity: 1
       }, 1000);
   }
   if(scrollY > 0 && $header.is(':not(:animated)')){
       $header.animate({
            opacity: .5
       }, 1000);
    }
 });