带有居中div的动画

时间:2015-03-05 12:58:24

标签: javascript jquery css

我有一个非常简单的布局,在较小的div中有一个较大的div,我想要制作动画:

<div style="
        position: relative;
        left:100px;
        width:200px;
        height:400px;
        background:red;
        overflow:visible"
>
    <div id="stamp" style="
            position:absolute;
            margin: 0 auto;
            bottom:-150px;
            width:200%;
            height:150px;
            background:blue"
    ></div>
</div>

JS:

$("#stamp").animate({
    bottom: "200",
    width: "150%"
}, 400, function() {
    $("#stamp").animate({
        width: '80%', 
    }, 220, function() {
        // Animation complete.
    });
});

JSFiddle Here

我想要什么,但无法弄清楚,我希望蓝色div居中,而不是左对齐。

因此蓝色div将开始居中,将动画起来(仍然居中),然后在动画之后蓝色div将居中于80%宽度。

3 个答案:

答案 0 :(得分:1)

所以最后蓝色div的宽度为80%。为什么不在蓝色div中添加保证金。

margin-left:10%;

JSFiddle

答案 1 :(得分:1)

对于初学者来说,如果所涉及的元素绝对定位,margin: 0 auto将不再具有所需的效果(居中)。

为了达到你想要的效果,我会抛弃position: absolute并使用负边距(需要设置动画以保持居中):

$("#stamp").animate
({
    bottom: "200",
    width: "150%",
    marginLeft: "-75%"
   
}, 400,
    function()
    {
        $( "#stamp" ).animate
        ({
            width: "80%",
            marginLeft: "-40%"
   
        }, 220, function() { /* complete */ });
});
#container
{
    position: relative;
    left:100px;
    width:200px;
    height:400px;
    background:red;
    overflow:visible;    
}
#stamp
{
    position:absolute;
    left: 50%;
    margin-left: -100%;
    bottom:-150px;
    width:200%;
    height:150px;
    background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
    <div id="stamp"></div>
</div>

(也在http://jsfiddle.net/maryisdead/g7vtbjns/

答案 2 :(得分:0)

对于居中的div更改你的CSS

{
  background: none repeat scroll 0 0 blue;
  bottom: 200px;
  height: 150px;
  margin: 0 auto;
  position: relative;
  top: 0;
  width: 80%;
  z-index: 1;
}

现在你将红色div中的div居中

检查这个小提琴 http://jsfiddle.net/7metw85n/1/