通过CSS3实现小火车动画,让您的页面更生动有趣!(SEO优化)

12 min read

好的,以下是一个css3画的小火车动画的代码实现:

HTML代码:

<div class="train">
  <div class="train-body">
    <div class="train-window"></div>
    <div class="train-wheel"></div>
    <div class="train-wheel"></div>
  </div>
  <div class="train-smokestack"></div>
</div>

CSS代码:

.train {
  position: relative;
  width: 150px;
  height: 80px;
  background-color: #dbd0c6;
  border-radius: 5px;
  overflow: hidden;
  animation: move 3s infinite ease-in-out;
  animation-delay: 0s;
}

@keyframes move {
  0% {
    left: 0;
  }
  50% {
    transform: translateX(100px);
  }
  100% {
    left: calc(100% + 150px);
  }
}

.train-body {
  position: absolute;
  top: 50%;
  left: 10%;
  transform: translateY(-50%);
  width: 80%;
  height: 60%;
  background-color: #8c8b8b;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .5);
}

.train-window {
  position: absolute;
  top: 25%;
  left: 20%;
  width: 20%;
  height: 40%;
  background-color: #e5fcfc;
  border-radius: 5px;
}

.train-wheel {
  position: absolute;
  top: 80%;
  left: 15%;
  width: 20px;
  height: 20px;
  background-color: #353535;
  border-radius: 50%;
}

.train-wheel:last-child {
  left: 65%;
}

.train-smokestack {
  position: absolute;
  top: 20%;
  left: 70%;
  width: 15%;
  height: 30%;
  background-color: #353535;
  border-radius: 5px;
}

在这段代码中,我们使用 @keyframes 声明了一个名为 move 的动画。该动画会将火车从最左侧移动到最右侧,然后在回到最左侧。我们设置每次动画的时间是 3 秒,并且设置 infiniteease-in-out,表示该动画会持续无限次,并且速度会有一个先慢后快再慢的变化。我们还设置了一个 animation-delay 属性,表示动画一开始就开始播放。

.train 选择器中,我们设置了容器的宽和高,以及背景颜色、边框圆角和溢出。我们还将 overflow 属性设置为 hidden,以确保火车的部分在容器外的部分不会被显示。

.train-body 选择器中,我们设置了火车车身的位置、宽度、高度、背景颜色、边框圆角和阴影。

.train-window 选择器中,我们设置了火车车窗的位置、宽度、高度、背景颜色和边框圆角。

.train-wheel 选择器中,我们设置了火车的车轮位置、宽度、高度、背景颜色和边框圆角。我们使用 last-child 选择器指定最后一个车轮的位置在最右侧。

最后,在 .train-smokestack 选择器中,我们设置了火车烟囱的位置、宽度、高度、背景颜色和边框圆角。

这样,在浏览器中查看 HTML 文件,就会看到一个小火车在页面上移动的动画。