CSS -- 实现摇晃的灯笼,中秋应景

1,135 阅读2分钟

在正文的第一句加入“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

先上效果

复习动画

animation

animation 属性是一个简写属性,用于设置六个动画属性:

  • animation-name
  • animation-duration
  • animation-timing-function
  • animation-delay
  • animation-iteration-count
  • animation-direction

animation-name

属性指定应用的一系列动画,每个名称代表一个由@keyframes定义的动画序列。

animation-duration

动画一个周期所需要的时间

animation-timing-function

animation-timing-function 使用名为三次贝塞尔(Cubic Bezier)函数的数学函数,来生成速度曲线。您能够在该函数中使用自己的值,也可以预定义的值

描述测试
linear动画从头到尾的速度是相同的。
ease默认。动画以低速开始,然后加快,在结束前变慢。
ease-in动画以低速开始。
ease-out动画以低速结束。
ease-in-out动画以低速开始和结束。
cubic-bezier(n,n,n,n)在 cubic-bezier 函数中自己的值。可能的值是从 0 到 1 的数值。

animation-delay

延迟

animation-iteration-count

定义动画的播放次数。

描述测试
n定义动画播放次数的数值。
infinite规定动画应该无限次播放。

animation-direction

描述测试
normal默认值。动画应该正常播放。测试
alternate动画应该轮流反向播放。

主要实现代码

灯笼整体形状

.lantern-light {
  position: relative;
  width: 120px;
  height: 90px;
  background-color: rgb(255, 0, 0);
  margin: 30px;
  border-radius: 50%;
  box-shadow: -5px 5px 50px 4px #ff6f00;
  transform-origin: top center;
  animation: swing 3s infinite ease-in-out;
}

灯笼顶部和底部

/* 灯笼顶部和底部的样式 */
.lantern-light::before,
.lantern-light::after {
  content: '';
  position: absolute;
  border: 1px solid #e9e5de;
  width: 60px;
  height: 12px;
  /* 背景渐变 */
  background: linear-gradient(
    to right,
    #e2c691,
    #ffa500,
    #dc8f03,
    #ffa500,
    #dc8f03
  );
  left: 30px;
}
 
/* 顶部位置 */
.lantern-light::before {
  top: -8px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}
 
/* 底部位置 */
.lantern-light::after {
  bottom: -7px;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

实现动画

.lantern-light {
  position: relative;
  width: 120px;
  height: 90px;
  background-color: rgb(255, 0, 0);
  margin: 30px;
  border-radius: 50%;
  box-shadow: -5px 5px 50px 4px #ff6f00;
  transform-origin: top center;
  animation: swing 3s infinite ease-in-out;
}
/* 灯笼的动画效果 */
@keyframes swing {
  0% {
    transform: rotate(-30deg);
  }
 
  50% {
    transform: rotate(15deg);
  }
 
  100% {
    transform: rotate(-30deg);
  }
}