學習鏈接:B站視頻
一、方塊沿盒子邊緣移動 (初步版)
演示
代碼
<body>
<main>
<div></div>
</main>
</body>
main {
width: 400px;
height: 400px;
border: 1px solid #ddd;
}
div {
width: 100px;
height: 100px;
background-color: #2980b9;
animation-name: hd; /* 設置關鍵幀的名字爲 hd */
animation-duration: 4s; /* 設置動畫持續時間 */
}
@keyframes hd { /* 定義關鍵幀 */
25% {
transform: translateX(300px); /* 偏移座標 */
}
50% {
transform: translate(300px, 300px);
}
75% {
transform: translateY(300px);
}
}
二、方塊沿盒子邊緣移動 (多個動畫疊加版)
演示
代碼
<body>
<main>
<div></div>
</main>
</body>
main {
width: 400px;
height: 400px;
border: 1px solid #ddd;
}
div {
width: 100px;
height: 100px;
background-color: #2980b9;
animation-name: hd, background, radius; /* 添加三個動畫幀 */
animation-duration: 4s, 2s, 2s; /* 設置動畫持續時間 */
}
@keyframes hd { /* 定義關鍵幀: 移動 */
25% {
transform: translateX(300px); /* 偏移座標 */
}
50% {
transform: translate(300px, 300px);
}
75% {
transform: translateY(300px);
}
}
@keyframes background { /* 定義關鍵幀:顏色 */
25% {
background-color: #2ecc71;
}
50% {
background-color: #f1c40f;
}
75% {
background-color: #8e44ad;
}
}
@keyframes radius { /* 定義關鍵幀: 圓角 */
25% {
border-radius: 50%;
}
50% {
border-radius: 0;
}
75% {
border-radius: 50%;
}
}