“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!”
最佳实践
日历双节切换
实现代码
代码解析
HTML代码
<div id="app">
<div class='noticeWrap'>
<div class='noticeRow' >中秋节</div>
<div class='noticeRow'>教师节</div>
</div>
</div>
在html中我们定义了 .noticeWrap
的一个盒子,里边包含所有的切换元素。
CSS代码
#app{
background-color: green;
}
.noticeWrap {
height: 22px;
overflow: hidden;
position: relative;
flex: 1;
width: 60px;
text-align: center;
line-height: 22px;
}
.noticeRow {
position: absolute;
height: 100%;
width: 100%;
}
@keyframes anim1 {
0% {
top: 0;
opacity: 1;
}
45% {
top: 0;
opacity: 1;
}
50% {
top: -100%;
opacity: 0;
}
51% {
top: 100%;
opacity: 0;
}
95% {
top: 100%;
opacity: 1;
}
96% {
opacity: 1;
}
100% {
top: 0;
opacity: 1;
}
}
@keyframes anim2 {
0% {
top: 100%;
opacity: 0;
}
45% {
top: 100%;
opacity: 0;
}
50% {
top: 0;
opacity: 1;
}
95% {
top: 0;
opacity: 1;
}
100% {
top: -100%;
opacity: 0;
}
}
.noticeRow:nth-child(1) {
animation: anim1 5s linear infinite;
}
.noticeRow:nth-child(2) {
top: 25px;
animation: anim2 5s linear infinite;
}
- 在父级
.noticeWrap
我们设置position: relative;
相对定位。子级.noticeRow
设定绝对定位,绝对定位会依据父元素中最近设置为relative定位类型的元素进行偏移。这样再通过配合“top”、“bottom”、“left”、“right”这4个偏移量来实现相对它所属父元素的相对定位来实现切换。 - 在子级中,我们通过 css3的
animation
(动画) 属性实现动态切换效果; 语法:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
值 | 说明 |
---|---|
name | 指定要绑定到选择器的关键帧的名称 |
duration | 动画指定需要多少秒或毫秒完成 |
timing-function | 设置动画将如何完成一个周期 |
delay | 设置动画在启动前的延迟间隔。 |
iteration-count | 定义动画的播放次数。 |
direction | 指定是否应该轮流反向播放动画。 |
fill-mode | 规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),要应用到元素的样式。 |
play-state | 指定动画是否正在运行或已暂停。 |
- 在
.noticeRow:nth-child(1)
第一个子集中,我们绑定了anim1
的每关键帧移动函数:
具体思路: 0%展示 -> 45%展示 -> 50%top:-100%隐藏在顶部 -> 51%top: 100%隐藏在底部-> 95%top: 100%隐藏在底部并展示 -> 96%过度展示 -> 100%展示
@keyframes anim1 {
0% {
top: 0;
opacity: 1;
}
45% {
top: 0;
opacity: 1;
}
50% {
top: -100%;
opacity: 0;
}
51% {
top: 100%;
opacity: 0;
}
95% {
top: 100%;
opacity: 1;
}
96% {
opacity: 1;
}
100% {
top: 0;
opacity: 1;
}
}
- 在
.noticeRow:nth-child(2)
第2个子集中,top: 25px;
初始隐藏在底部,运动函数anim2
与anim1
逻辑相反。 - 关于
animation
的属性可查看animation
常用的CSS动画库
- Animista 是一个在线动画生成器,同时也是一个动画库。
- Animate CSS 齐全的CSS3动画库。
总结
动画是使元素从一种样式逐渐变化为另一种样式的效果。可以改变任意多的样式任意多的次数。
动画是 CSS3
中最具颠覆性的特征之一,可通过设置多个节点来精确的控制一个或者一组动画,从而实现复杂的动画效果, 推荐实现动画尽量使用 css
实现, 以避免操作 dom
产生 回流
与 重绘
。