2014-11-25 38 views
0

我有一个fiddlejQuery的动画第一次运行不滑动

基本上你第一次徘徊,我想.caption-2逐渐下滑,而不是“跳”起来。第一次徘徊后,一切都很好。

任何想法如何实现这一目标?

HTML

<div class="caption-img"> 
    <div class="headline"> 
     <h2>You should Study here</h2> 
    </div> 
    <div class="caption-2"> 
     <p>Learning at a place puts you in the driving seat as you set off on the journey 
      to your dream career. Whether you want to become a chef, a mechanic, a builder,</p> 
     <p>Learning at nice place puts you in the driving seat as you set off on the journey 
      to your dream career. Whether you want to become a chef, a mechanic, a builder,</p> 
    </div> 
</div> 

jQuery的

$(".caption-img").hover(function() { 
    $(".headline").hide(); 
    $(".caption-2").show().stop().animate({"top" : "0px"}); 
}, function() { 
    $(".caption-2").stop().animate({"top" : "250px"}); 
    setTimeout(function() { 
     $(".caption-2").hide(); 
     $(".headline").show(); 
    }, 300); 
}); 

CSS

.headline { 
    padding: 10px; 
    font-size: 11px; 
    color: white; 
    background: rgba(0, 154, 202, 0.7); 
    position: absolute; 
    bottom: 0px; 
    width:100%; 
} 
.caption-2 { 
    padding: 10px; 
    font-size: 11px; 
    color: white; 
    background: rgba(0, 154, 202, 0.7); 
    position: absolute; 
    bottom: 0px; 
} 

.caption-img { 
    height: 320px; 
    position: relative; 
    background: #E9EAEC url(http://upload.wikimedia.org/wikipedia/commons/3/3d/Northwest-relief_HazeltonMountains.jpg); 
    background-size:contain; 
} 

.caption-2 {display:none;} 

回答

1

.caption-2没有初始top CSS值。 jQuery .animate()在动画的每一端都需要一个数值才能成功地为元素设置动画。只需设置初始top风格.caption-2

.caption-2 { 
    padding: 10px; 
    font-size: 11px; 
    color: white; 
    background: rgba(0, 154, 202, 0.7); 
    position: absolute; 
    top: 250px; 
    bottom: 0px; 
} 

此外,不要使用setTimeout()切换你的标题。由于.animate()需要回调函数;调用一个函数在动画完成的时候,你可以使用:

$(".caption-img").hover(function() { 
    $(".headline").hide(); 
    $(".caption-2").show().stop().animate({"top" : "0px"}); 
}, function() { 
    $(".caption-2").stop().animate({"top" : "250px"}, 400, function(){ 
     $(this).hide(); 
     $(".headline").show(); 
    }); 
}); 

JSFiddle