CSS3 Animation实现走马灯轮播
前言:
实现轮播效果的插件数不胜数,但过于绚烂的效果也会占用较高的CPU,可能导致卡顿。今天演示一个用纯CSS实现横向轮播的流畅动画案例
实现:
实质就是在画布内利用animation动画,通过margin来控制内容的偏移量,隐藏不在画布内的元素,达到轮播的效果
HTML:
.wrapper:画布
.container:动画区
.content:每一帧动画
<div class="wrapper">
<div class="container">
<div class="content">
<h1>1</h1>
</div>
<div class="content">
<h1>2</h1>
</div>
<div class="content">
<h1>3</h1>
</div>
</div>
</div>
css:
// 画布
.wrapper {
display: flex;
width: 300px;
height: 300px;
overflow: hidden;
border: 3px solid #CCC;
}
// 动画区
// animation属性 名为switch 动画播放时长为9s、以ease-out方式进行播放、循环播放(infinite)
.container {
animation: switch 9s ease-out infinite;
display: flex;
align-items: center;
// 动画帧
.content {
float: left;
width: 280px;
height: 280px;
margin-right: 20px;
color: #FFF;
&:nth-child(1) {
background-color: #e4393c;
}
&:nth-child(2) {
background-color: #c1e3ff;
}
&:nth-child(3) {
background-color: #6de195;
}
}
}
// 创建了一个@keyframes命名为switch,区分三个阶段进行轮播
// 33.1%~33.5%, 67%~67.4%代表动画过度阶段
@keyframes switch {
0%, 33.1% {
margin-left: 10px;
}
33.5%, 67% {
margin-left: -290px;
}
67.4%, 100% {
margin-left: -590px;
}
}