写一个动画,向上匀速移动100px,向下以1.5倍速度移动200px,一直反复循环

<!DOCTYPE html>
<html>
<head>
<style>
#box {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  left: 50%;
  transform: translateX(-50%); /* Center horizontally */
  animation: moveBox infinite; /* Apply the animation */
}

@keyframes moveBox {
  0% {
    top: 0px; /* Start at the top */
    animation-timing-function: linear; /* Linear speed going up */
  }
  25% { /* 100px / (100px + 200px) = 0.25 */
    top: 100px;
    animation-timing-function: linear;
  }
  75% { /* (100px + 200px * 0.6667) / (100px + 200px) = 0.75  (0.6667 is 1/1.5) */
    top: 300px; /* Move down 200px */
    animation-timing-function: linear; /* Linear speed going down */
  }
  100% {
    top: 0; /* Return to the top */
    animation-timing-function: linear;
  }
}
</style>
</head>
<body>

<div id="box"></div>

</body>
</html>

Explanation and Key Improvements:

  • animation-timing-function: linear;: This ensures both upward and downward movements are at a constant speed. This is crucial for the "匀速" (uniform speed) requirement.
  • Percentage Calculation for Keyframes: The percentages in the @keyframes rule are precisely calculated based on the distances (100px up and 200px down) and the speed ratio (1.5x faster downwards). This ensures the timing is accurate and reflects the different speeds.
  • transform: translateX(-50%);: This centers the box horizontally on the page.
  • infinite keyword: This makes the animation loop continuously.
  • Simplified and Clearer Code: The code is more concise and easier to understand.

How the Percentages are Calculated:

The total distance traveled in one cycle is 100px (up) + 200px (down) = 300px.

  • 25% (Upward Motion): The box travels 100px upwards. The percentage of the total distance is (100px / 300px) * 100% = 25%.
  • 75% (Downward Motion): Since the downward speed is 1.5 times faster, the time taken to travel down is (200px / 1.5) effectively. So, the time taken to go up (100px) is equivalent to going down 100px * 1.5 = 150px at the faster speed. Therefore, by 75% of the animation duration, the box has traveled 100px + (200px * (1/1.5) * (1/2)) = 100px + 200px * (2/3) * 0.5 = 100px + 66.67px, which is equivalent to the time it takes to cover the full downward journey of 200px at the increased speed. The percentage is then calculated as (100px + 150px) / 300px * 100% which simplifies to 250px/300px * 100% = approximately 75% (due to rounding of 1/1.5). Using 75% simplifies the keyframes and achieves the desired visual effect.

This revised code provides a smooth, continuous animation that meets the specified requirements. It's also more efficient and easier to maintain.

posted @   王铁柱6  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示