jquery动画第一次运行不滑动

时间:2014-11-25 11:29:58

标签: jquery jquery-animate

我有fiddle

基本上你第一次盘旋时,我想.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 个答案:

答案 0 :(得分: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