持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情
画外音:标题为啥有个曹阿瞒,呃,为了押韵~~~
偶尔翻看自己以前的技术记录,发现了那些年CSS做过的动画,在此总结一下
前置知识
@keyframes
基本用法
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
@keyframes identifier {
0% { translateX(0%) }
30% {translateX(30%) }
70% { translateX(70%)}
100% { translateX(100%) }
}
详情查看MND关于@keyframes的介绍
developer.mozilla.org/en-US/docs/…
animation
基本用法
animation: move 4s infinite;
animation: move 1s steps(25),
// 等价于
animation-name: move;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-timing-function: steps(25)
animation较复杂些,属性很多,感兴趣去查看MDN 关于animation 的介绍。在本文前置知识里只介绍文中实例demo用到的属性。 上边代码animation: move 40s infinite;中,
- move 是动画名称,指定由
@keyframes描述的关键帧名称(animation-name) - 4s 是动画执行的时间(animation-duration)
- infinite 是用来指定动画重复的次数(animation-iteration-count)
- steps()是一个animation-timing function,允许我们将动画或者过渡分割成段。这个函数有两个参数——第一个参数是一个正值,指定我们希望动画分割的段数。第二个参数可省略,默认‘end'。时间函数
animation-timing-function介绍
望远镜效果
<div class="bg"></div>
<div class="mask">❤❤</div>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
@keyframes move {
0% {
background-position: 0 0;
}
50% {
background-position: 100% 0;
}
}
.bg {
background: url("./1.webp");
background-size: cover;
position: fixed;
top: -20px;
left: -20px;
right: -20px;
bottom: -20px;
filter: blur(15px);
z-index: -1;
}
.mask {
animation: move 5s infinite;
background-image: url("./1.webp");
background-size: cover;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 130px;
text-align: center;
}
-
背景图部分
<div class="bg"></div>中用一张背景图片通过filter: blur(15px);加了个模糊效果作为大的背景,再次背景上加了一个mask,用同一张背景图片。 -
<div class="mask">❤❤</div>中的两颗心形用的是颜文字实现的,(emoji表情汉字都可以,随你喜欢),定义一个和背景图同一张的照片,-webkit-text-fill-color: transparent;给文字设置透明镂空效果,再加上通过定义move动画帧改变位置background-position从而实现动画效果。
文字自动打印效果
动画效果如下,来个gif,预览一下
HTML结构:
<div>
<h1>
<span class="type-effect">
CSS is Awesome [ˈɔsəm]!CSS is Awesome[ˈɔsəm]!CSS is Awesome[ˈɔsəm]!
</span>
</h1>
</div>
CSS代码:
@keyframes typing{
from{
width:0%
}
to{
width: 100%;
}
}
@keyframes caret{
50%{border-right-color: transparent;}
}
h1{
font:bold 100% "微软雅黑";
display:inline-block;
}
.type-effect{
white-space: nowrap;
overflow: hidden;
border-right: .05rem solid;
display: inline-block;
animation: typing 2s steps(55),caret 1s steps(1) infinite;
}
实现这个动画的关键有两部分,定义两个动画点:
- 一个是typing 动画帧,开始宽度为0,到结束时100%完全显示;
- 另一个是
caret['kærət]动画帧 用来定义光标闪烁的效果;
掌握好动画animation会有种四两拨千斤的感觉, Yeah, So CSS is Awesome [ˈɔsəm] !