纯CSS实现文字动态上下切换效果

1,221 阅读3分钟

“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

最佳实践

日历双节切换

121312324.gif

实现代码

代码解析

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;
}
  1. 在父级 .noticeWrap 我们设置 position: relative; 相对定位。子级 .noticeRow 设定绝对定位,绝对定位会依据父元素中最近设置为relative定位类型的元素进行偏移。这样再通过配合“top”、“bottom”、“left”、“right”这4个偏移量来实现相对它所属父元素的相对定位来实现切换。
  2. 在子级中,我们通过 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指定动画是否正在运行或已暂停。
  1. .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;
  }
}
  1. .noticeRow:nth-child(2) 第2个子集中,top: 25px; 初始隐藏在底部,运动函数 anim2anim1 逻辑相反。
  2. 关于 animation 的属性可查看animation

常用的CSS动画库

  1. Animista 是一个在线动画生成器,同时也是一个动画库。
  2. Animate CSS 齐全的CSS3动画库。

总结

动画是使元素从一种样式逐渐变化为另一种样式的效果。可以改变任意多的样式任意多的次数。

动画是 CSS3 中最具颠覆性的特征之一,可通过设置多个节点来精确的控制一个或者一组动画,从而实现复杂的动画效果, 推荐实现动画尽量使用 css 实现, 以避免操作 dom 产生 回流重绘