这段代码创建了一个炫酷的PK特效,其中正方(红色)和反方(蓝色)各有一个长条形代表,并且两个长条在同一水平线上咬合在一起。红色长条中间有字符 “P”,蓝色长条中间有字符 “K”,字符颜色为白色。我们为红色和蓝色长条分别定义了动画,并确保它们从两侧向中间碰撞在一起。
关键点总结
- 基本布局
- 使用 Flexbox 布局使内容居中。
- 设置页面高度为视口高度,并移除默认边距。
- PK 容器
- 设置相对定位,宽度为360px,高度为200px,以适应两个不同宽度的长条。
- 战斗者样式
- 使用绝对定位控制长条的位置。
- 长条的高度为40px,文本居中显示,颜色为白色,字体大小为24px,粗体。
- 红色战斗者
- 背景颜色为红色。
- 初始位置在左侧外侧 (
left: -155px)。 - 宽度为190px。
- 使用多边形裁剪路径创建斜切效果 (
clip-path: polygon(0 0, 190px 0, 165px 40px, 0 40px))。 - 应用碰撞动画 (
animation: collision-red 2s infinite alternate)。
- 蓝色战斗者
- 背景颜色为蓝色。
- 初始位置在右侧外侧 (
right: -155px)。 - 宽度为150px。
- 使用多边形裁剪路径创建斜切效果 (
clip-path: polygon(25px 0, 150px 0, 150px 40px, 0 40px))。 - 应用碰撞动画 (
animation: collision-blue 2s infinite alternate)。
- 动画效果
@keyframes collision-red:定义红色长条从初始位置到最终位置的动画 (to { left: 35px; })。@keyframes collision-blue:定义蓝色长条从初始位置到最终位置的动画 (to { right: 35px; })。
这些关键点确保了红色和蓝色长条能够从两侧向中间碰撞在一起,并且保持各自的形状和位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
overflow: hidden;
}
.pk-container {
position: relative;
width: 360px; /* 容器宽度以适应两个不同宽度的长条 */
height: 200px;
}
.fighter {
position: absolute;
height: 40px; /* 增加高度以便更好地显示斜切效果 */
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 24px;
font-weight: bold;
}
.red-fighter {
background-color: red;
top: 90px;
left: -155px; /* 初始位置在左侧外侧 */
width: 190px; /* 红色长条宽度为190px */
clip-path: polygon(0 0, 190px 0, 165px 40px, 0 40px);
animation: collision-red 2s infinite alternate;
}
.blue-fighter {
background-color: blue;
top: 90px;
right: -155px; /* 初始位置在右侧外侧 */
width: 150px; /* 蓝色长条宽度为150px */
clip-path: polygon(25px 0, 150px 0, 150px 40px, 0 40px);
animation: collision-blue 2s infinite alternate;
}
@keyframes collision-red {
to {
left: 35px; /* 最终位置在左侧 */
}
}
@keyframes collision-blue {
to {
right: 35px; /* 最终位置在右侧 */
}
}
</style>
</head>
<body>
<div class="pk-container">
<div class="fighter red-fighter">P</div>
<div class="fighter blue-fighter">K</div>
</div>
</body>
</html>

No responses yet