用velocity.js动画div到中心?

时间:2016-02-16 10:44:52

标签: javascript jquery html css velocity.js

我有一个div列表,我想用速度来动画第一项。该动作应该是div变成圆形并且具有不同的颜色并且仍然保持居中。

HTML的代码

<div id="container">
    <div class="paper"><h3>Box 1</h3></div>
    <div class="paper"><h3>Hello Word</h3></div>
    <div class="paper"><h3>2 + 2 = 5</h3></div>
    <div class="paper"><h3>Final box</h3></div>
</div>

对于CSS

body{
    background-color: #F5F5F5;
}
#container{
    width: 80%;
    margin-left: auto;
    margin-right: auto;
}
.paper{
    width: 100%;
    height: 100px;
    background-color: #fff;
    margin-top: 10px;
    box-shadow: 1px 3px 4px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
    line-height: 100px;
    text-align: center;
}
.paper:hover{
    background-color: #607D8B;
    color: white;
}

和js代码:

 window.onload = function(){
            var $box1 = $('.paper').eq(0);
            $box1.on("click",function(){
                $box1.velocity({borderRadius: '50%',
                                width:'100px',
                                backgroundColor:'#4CAF50',
                                color:'#fff',
                                marginLeft:'auto',
                                marginRight:'auto'
                                },
                               {duration:500,easing:'easeInQuad'});
            });

        }

基本上一切都有效,除了点击的div总是动画到容器的左侧部分。我认为将MarginLeft和MarginRight设置为auto会阻止这种情况,但显然不会(但是将MarginLeft设置为40%有效)。我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用flexbox保持中心。

在您的示例中,我刚将此属性添加到您的容器

display:flex;
flex-direction: column;
align-items: center;

检查这个工作小提琴

&#13;
&#13;
var $box1 = $('.paper').eq(0);
            $box1.on("click",function(){
                $box1.velocity({borderRadius: '50%',
                                width:'100px',
                                backgroundColor:'#4CAF50',
                                color:'#fff'
                                },
                               {duration:500,easing:'easeInQuad'});
            });
&#13;
body{
    background-color: #F5F5F5;
}
#container{
    width: 80%;
    margin-left: auto;
    margin-right: auto;
		display:flex;
		flex-direction: column;
		align-items: center;
		
}
.paper{
    width: 100%;
    height: 100px;
    background-color: #fff;
    margin-top: 10px;
    box-shadow: 1px 3px 4px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
    line-height: 100px;
    text-align: center;
}
.paper:hover{
    background-color: #607D8B;
    color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
<div id="container">
    <div class="paper"><h3>Box 1</h3></div>
    <div class="paper"><h3>Hello Word</h3></div>
    <div class="paper"><h3>2 + 2 = 5</h3></div>
    <div class="paper"><h3>Final box</h3></div>
</div>
&#13;
&#13;
&#13;