通过结合@keyframes
动画,让三角形实现旋转、移动等动态效果
代码如下:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>带动画的CSS三角形示例</title><style>body {font-family: Arial, sans-serif;display: flex;justify-content: center;align-items: center;min-height: 100vh;background-color: #f4f4f4;margin: 0;}.container {text-align: center;}h2 {font-size: 1.5rem;color: #333;margin-bottom: 10px;}.triangle {margin: 20px;animation-duration: 4s;animation-iteration-count: infinite;animation-timing-function: ease-in-out;}/* 向上的三角形,结合旋转动画 */.triangle-up {width: 0;height: 0;border-left: 50px solid transparent;border-right: 50px solid transparent;border-bottom: 100px solid #3498db;animation-name: rotate;}/* 向下的三角形,结合上下移动动画 */.triangle-down {width: 0;height: 0;border-left: 50px solid transparent;border-right: 50px solid transparent;border-top: 100px solid #e74c3c;animation-name: move-up-down;}/* 向左的三角形,结合左右移动动画 */.triangle-left {width: 0;height: 0;border-top: 50px solid transparent;border-bottom: 50px solid transparent;border-right: 100px solid #2ecc71;animation-name: move-left-right;}/* 向右的三角形,结合缩放动画 */.triangle-right {width: 0;height: 0;border-top: 50px solid transparent;border-bottom: 50px solid transparent;border-left: 100px solid #f1c40f;animation-name: scale;}/* 旋转动画 */@keyframes rotate {0% {transform: rotate(0deg);}50% {transform: rotate(180deg);}100% {transform: rotate(360deg);}}/* 上下移动动画 */@keyframes move-up-down {0%, 100% {transform: translateY(0);}50% {transform: translateY(-50px);}}/* 左右移动动画 */@keyframes move-left-right {0%, 100% {transform: translateX(0);}50% {transform: translateX(-50px);}}/* 缩放动画 */@keyframes scale {0%, 100% {transform: scale(1);}50% {transform: scale(1.5);}}</style> </head> <body><div class="container"><h2>带动画的CSS三角形示例</h2><div class="triangle triangle-up"></div><div class="triangle triangle-down"></div><div class="triangle triangle-left"></div><div class="triangle triangle-right"></div></div> </body> </html>
动画效果解析:
-
旋转动画 (
rotate
): 向上的三角形会不断旋转,从0度到360度形成循环。
@keyframes rotate {0% {transform: rotate(0deg);}50% {transform: rotate(180deg);}100% {transform: rotate(360deg);} }
2.上下移动动画 (move-up-down
): 向下的三角形在垂直方向上移动,模拟“跳动”效果。
@keyframes move-up-down {0%, 100% {transform: translateY(0);}50% {transform: translateY(-50px);} }
3.左右移动动画 (move-left-right
): 向左的三角形在水平方向上左右移动。
@keyframes move-left-right {0%, 100% {transform: translateX(0);}50% {transform: translateX(-50px);} }
4.缩放动画 (scale
): 向右的三角形会在大小之间切换,模拟“脉动”效果。
@keyframes scale {0%, 100% {transform: scale(1);}50% {transform: scale(1.5);} }