2017-04-21 46 views
0

我有以下的HTML布局:为什么jquery animate()不适用于我的情况?

<html> 
    <head> 
     ... 
    </head> 
    <body> 
     <header class="fluid-container"> 
      <div class="nav-wrapper"> 
       ... 
      </div> 
     </header> 
     <section class="salutation fluid-container"> 
      <div class="intro-wrapper"> 
       ... 
      </div> 
     </section> 
    </body> 
</html> 

我的目标是隐藏介绍,包装每当我的窗口滚动比60像素更反之亦然。因此,我已经实现了以下JQuery代码来实现上述目标。

var checkScroll = true; 

$(window).scroll(function() { 

    if($(this).scrollTop() > 60 && checkScroll) { 
     $(".intro-wrapper").stop().animate({display:'none'}, 400); 
     checkScroll = false; 
     console.log('Scrolling down. \t checkScroll: ' + checkScroll); 
    } 

    else if($(this).scrollTop() < 60 && !checkScroll) { 
     $(".intro-wrapper").stop().animate({display:'block'}, 400); 
     checkScroll = true; 
     console.log('Scrolling up. \t\t checkScroll: ' + checkScroll); 
    } 
}); 

但不幸的是,我一直无法理解为什么动画没有发生。请指出我上面的代码中的错误,并帮助我找出解决方案。

请注意console.log()正在呈现的结果,正如预期,即条件越来越适当满足,环适当完成其旅程。

回答

1

display将不会与animate一起使用。除了其他答案之外,您可以改为使用show()hide()

http://api.jquery.com/animate/

注意:与速记动画的方法,如.slideDown()和.fadeIn()时,.animate()方法不会使隐藏的元件的效果的一部分是可见的。例如,给定$(“someElement”).hide()。animate({height:“20px”},500),动画将运行,但元素将保持隐藏状态。

1

而是有生的在这里你可以使用jQuery .fadeIn().fadeOut()方法来显示或隐藏元素有延迟。

显示属性不会在jQuery的动画作品。 参考animate

+0

好吧,我明白你的意思。但为什么不'animate()'工作? – ikartik90

+0

http://api.jquery.com/animate/浏览此链接中黄色突出显示的注释。 –

0

显示为none /块不能被动画。会转而溢出动画的高度,以0:隐藏

或者你可以用CSS过渡容易做到这一点:

// hide it 
$(".intro-wrapper").addClass('hidescroll'); 
// show it again 
$(".intro-wrapper").removeClass('hidescroll'); 

然后在CSS:

.intro-wrapper { 
    transition: height .5s ease-in; 
    height: 400px; 
} 

.intro-wrapper.hidescroll { 
    height: 0; 
    overflow: hidden; 
} 
相关问题