【问题标题】:Animate if scrollTop less than specified value - does not work如果 scrollTop 小于指定值则动画 - 不起作用
【发布时间】:2012-11-03 07:10:36
【问题描述】:

ease-scroll 是一个带有一个锚标记的 div。

<div id="ease-scroll">
    <a href="#">&uarr; Top</a>      
</div>

当 scrollTop() 大于 450 时,我需要 div 的不透明度为 0.9,这可以按预期工作,如果我现在滚动 up 从而 scrollTop() 值小于 450,我想要将不透明度恢复为原始值 0.1。但是,恢复不透明度值没有发生。 有什么线索吗?

// Help navigate!
jQuery(window).scroll(function () { 
    if ( jQuery(window).scrollTop() > 450 && jQuery("#ease-scroll").css("opacity") != 0.9 ) {
       jQuery("#ease-scroll").animate( {opacity: 0.9}, 'medium');
    }
    if ( jQuery(window).scrollTop() < 450 && jQuery("#ease-scroll").css("opacity") != 0.1 ) {
        jQuery("#ease-scroll").animate( {opacity: 0.1}, 'medium');
    }
});

【问题讨论】:

  • 如果 jQuery(window).scrollTop() == 450 那么怎么办??
  • @Peter O. 避免这样小的编辑更改。我们的社区不欢迎它。

标签: jquery jquery-animate scrolltop


【解决方案1】:

jsBin demo

jQuery(function( $ ){

   $(window).scroll(function(){
       
      var scrolled = $(window).scrollTop();
      $("#ease-scroll").stop().animate({opacity: (scrolled>450 ? 0.9 : 0.1) }, 600);

   });

});

【讨论】:

  • 谢谢。这很有帮助,尽管我不得不更改 $('body').scrollTop();到 $(window).scrollTop() 也许,它在 jsBin 中工作,因为它的主体在一个在那里滚动的 iframe 内。
【解决方案2】:

当用户滚动时,滚动事件会被触发很多次。对每个事件使用 animation() 不是一个好主意,因为它会占用用户 CPU 资源。

这是一个解决方法:

// Help navigate!
jQuery(window).scroll(function () { 
    jQuery("#ease-scroll").stop(); // stop animation before anything else
    if ( jQuery(window).scrollTop() >= 450 && jQuery("#ease-scroll").css("opacity") != 0.9 ) {
       jQuery("#ease-scroll").animate( {opacity: 0.9}, 'medium');
    }
    if ( jQuery(window).scrollTop() < 450 && jQuery("#ease-scroll").css("opacity") != 0.1 ) {
        jQuery("#ease-scroll").animate( {opacity: 0.1}, 'medium');
    }
});

但是您应该定义一个 setTimeOut,如果需要,它会被重置以避免 CPU 无用(未经测试,可能的小语法错误:o)

// Help navigate!
var animationTimeout = null;
jQuery(window).scroll(function () { 

    // Clear planned animation
    clearTimeout(animationTimeout);

    // Define animation start after 500 ms if no others scroll events occurred

    if ( jQuery(window).scrollTop() >= 450 && jQuery("#ease-scroll").css("opacity") != 0.9 ) {
        animationTimeout = setTimeout(function(){
        jQuery("#ease-scroll").stop();
        jQuery("#ease-scroll").animate( {opacity: 0.9}, 'medium');
        },500);
    } 
    if ( jQuery(window).scrollTop() < 450 && jQuery("#ease-scroll").css("opacity") != 0.1 ) {
        animationTimeout = setTimeout(function(){
        jQuery("#ease-scroll").stop();
        jQuery("#ease-scroll").animate( {opacity: 0.1}, 'medium');
        },500);
    }
});

【讨论】:

  • 感谢您解释资源使用情况。当为调试添加的alert()多次触发时,我实际上想到了它,无法弄清楚如何停止()。它按原样工作没有语法错误:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 2017-10-15
相关资源
最近更新 更多