这是我参与「第四届青训营 」笔记创作活动的第三天
前端三件套各司其职之CSS动画
写这篇笔记其实更多的是为了探索css动画吧
受限于个人的开发经历,没有经历过曾经的css时代,在我开始学习前端的时候,就已经进入了css3时代,而CSS3中增加了许多的动画属性,如animation transition,在借助这些新的属性后,其实是可以用css做出很多动画的,至少个人看来,只要作者有耐心,未必不能做出非常精美的动画(因为个人曾经玩过blender、C4D等动画软件,无论是K帧还是调曲线,都是可视化的方式,非常方便,而CSS的动画需要手动去写贝塞尔曲线,对我来说非常痛苦)
于是,我就制作了一个简单的CSS交互动画,也许有人会问:你这个比起绑定一个onclick的优势是什么,我只能回答:没有什么优势,甚至会拖慢开发速度,但我觉得这算是设计与技术的不同点吧,设计时不能为自己考虑,而技术很多时候就是因为为自己考虑了而发生了进步。
这些案例仅仅是为了做一个探索,我在制作真实页面时依然会使用onclick来变换类名实现交互效果
代码逻辑
- 采用
label+checkbox制作,将checkbox隐藏
- 将label附着在点击的目标上,点击label相当于点击checkbox
- 通过伪类元素与父子选择器,传递到目标上
- 制作动画
上代码(仅包含关键部分):
:root {
--line-height: 8px;
--line-space: 14px;
--menu-height: 3 * var(--line-height) + 2 * var(--line-space);
--time-first-stage: 0.3s;
}
.menu {
width: 80px;
z-index: 10;
height: var(--menu-height);
cursor: pointer;
}
.line-white {
width: 100%;
height: var(--line-height);
background: #fff;
border-radius: 3px;
box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.3);
}
.number1 {
transform: translateY(0) rotateZ(0);
animation-name: first-line-exit;
animation-timing-function: ease-in-out;
animation-duration: 0.6s;
}
@keyframes first-line-exit {
from {
transform: translateY(22px) rotateZ(-45deg);
}
40% {
transform: translateY(22px) rotateZ(0deg);
}
50% {
transform: translateY(22px) rotateZ(0deg);
}
to {
transform: translateY(0px) rotateZ(0deg);
}
}
.number3 {
transform: translateY(0) rotateZ(0);
animation-name: third-line-exit;
animation-timing-function: ease-in-out;
animation-duration: 0.6s;
}
@keyframes third-line-exit {
from {
transform: translateY(-22px) rotateZ(45deg);
}
40% {
transform: translateY(-22px) rotateZ(0deg);
}
50% {
transform: translateY(-22px) rotateZ(0deg);
}
to {
transform: translateY(0px) rotateZ(0deg);
}
}
.number2 {
margin: var(--line-space) 0;
opacity: 1;
transition: opacity 1s;
}
#modeCheckBox:checked ~ .frame .menu .number1 {
transform: translateY(22px) rotateZ(-45deg);
animation-name: first-line-enter;
animation-timing-function: ease-in-out;
animation-duration: 0.6s;
}
@keyframes first-line-enter {
from {
transform: translateY(0px) rotateZ(0deg);
}
50% {
transform: translateY(22px) rotateZ(0deg);
}
60% {
transform: translateY(22px) rotateZ(0deg);
}
to {
transform: translateY(22px) rotateZ(-45deg);
}
}
#modeCheckBox:checked ~ .frame .menu .number2 {
opacity: 0;
transition: opacity var(--time-first-stage);
}
#modeCheckBox:checked ~ .frame .menu .number3 {
transform: translateY(-22px) rotateZ(45deg);
animation-name: third-line-enter;
animation-timing-function: ease-in-out;
animation-duration: 0.6s;
}
@keyframes third-line-enter {
from {
transform: translateY(0px) rotateZ(0deg);
}
50% {
transform: translateY(-22px) rotateZ(0deg);
}
60% {
transform: translateY(-22px) rotateZ(0deg);
}
to {
transform: translateY(-22px) rotateZ(45deg);
}
}
完整代码可以参考我的github