2014-11-25 57 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