开发者

I'm using the jQuery .scroll() function, why can't I override its effects with another function?

I'm using the jQuery .scroll() function to make a certain element fade to 0.2 opacity开发者_运维技巧. Since there is no native "scrollstop" indicator, I decided to make the element fade back to 1.0 opacity on hover. However, it doesn't work.

Here's my code:

$(document).ready(function() {  
$(window).scroll(function() {
    $("#navlist").animate({ opacity: 0.2 }, 2000);
});

$("#navlist").hover(    
    function() {
        $(this).animate({ opacity: 1 }, 500);
    }, function() {
        $(this).animate({ opacity: 1 }, 500); // just to be safe?
    }
);
});

When I scroll, the #navlist element fades, but when you hover over it nothing happens. But if you refresh the page when you're half way down, the element automatically fades as soon as you refresh, before I've scrolled, and if you try to hover to fade it back in, nothing happens.

Any thoughts?


try to stop animation first

$(document).ready(function() {  
$(window).scroll(function() {
    $("#navlist").stop().animate({ opacity: 0.2 }, 2000);

});
$("#navlist").hover(function() {
    $("#navlist").stop().animate({ opacity: 1.0 }, 500);
},
function() {
    $("#navlist").stop().animate({ opacity: 1.0 }, 500);
}
);


The problem is that the scroll event, gets called multiple times during a single scroll (10-20 per a single mouse wheel scroll), so #navlist gets a lot of animate events of 2 seconds.

I am not exactly sure what's going on with jQuery, but when you hover it, even though the opacity: 1 animations run, they end up running the queued #navlist animations.

I solved the problem using a sort of flag, I bet you can find something more efficient.

$(document).ready(function(){
   var isAnimationBusy = false;
   $(window).scroll(function(){
      if(isAnimationBusy) return;
      isAnimationBusy = true;
      $("#navlist").animate(
         { opacity: 0.2 }, 2000, 
         function(){ isAnimationBusy = false; }
      );
   });

   $("#navlist").hover(
      function(){
        isAnimationBusy = false;
         $(this).stop().animate({ opacity: 1 }, 500);
      },
      function(){
         isAnimationBusy = false;
         $(this).stop().animate({ opacity: 1 }, 500);
      }
   );
});

Edit: The animation stop will solve the problem, I still believe you should control how many times you call the animate event. There could be a performance hit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜