You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery Keyframes实现车轮旋转时未绕自身中心问题排查求助

问题成因与解决方案

你的车轮出现圆周运动而非绕自身中心旋转的核心原因有两个:

  • 动画应用对象错位:你把旋转动画绑定在了.wheel1/.wheel2容器上,但容器内的<img>元素通过position: relative设置了top和left偏移,导致图片的位置和容器的中心完全不重合。此时旋转容器,图片会绕着容器的中心(而非自身中心)做圆周运动。
  • 容器尺寸未匹配:.wheel1/.wheel2容器本身没有设置宽高,默认是 inline 元素的最小包裹尺寸,再加上图片的偏移,进一步加剧了旋转中心的错位。

快速修复方案:将动画直接绑定到图片元素

最简单的解决方式是把旋转动画的目标从容器改成里面的<img>——图片本身的transform-origin默认就是自身中心(50% 50%),只要旋转图片,就会绕自己的中心转动。

修改你的JS播放动画部分的代码:

function play(animation) { 
  $('.track').resetKeyframe(function() { 
    switch (animation) { 
      case 'normal': 
        // 把选择器从.wheel1改成.wheel1 img
        $('.wheel1 img').playKeyframe({ 
          name: 'wheelRotation', 
          duration: "5000ms", 
          timingFunction: 'linear', 
          iterationCount: 'infinite' 
        }); 
        $('.wheel2 img').playKeyframe({ 
          name: 'wheelRotation', 
          duration: "5000ms", 
          iterationCount: 'infinite', 
          timingFunction: 'linear' 
        }); 
        // 其他动画代码保持不变
        $('.track').playKeyframe({ name: 'carMove', duration: "13s", timingFunction: 'linear', iterationCount: 'infinite', direction: 'normal', fillMode: 'forwards' }); 
        $('.car').playKeyframe({ name: 'shake', duration: "3s", timingFunction: 'linear', iterationCount: 'infinite', direction: 'normal', fillMode: 'forwards' }); 
        break; 
    } 
  }) 
}

更规范的优化方案:调整容器与图片的布局

如果希望保持动画绑定在容器上,建议重构布局,让容器和图片的位置重合,避免用position: relative偏移图片:

  1. 给.wheel1/.wheel2容器设置与图片一致的宽高,并通过容器的定位调整位置,而不是偏移图片:
.wheel1 {
  width: 210px;
  height: 210px;
  position: relative;
  top: -320px;
  left: 42px;
}
.wheel1 img {
  width: 100%;
  height: 100%;
}

.wheel2 {
  width: 225px;
  height: 225px;
  position: relative;
  top: -540px;
  left: 255px;
}
.wheel2 img {
  width: 100%;
  height: 100%;
}
  1. 此时再给容器应用旋转动画,图片会跟着容器绕自身中心旋转——因为容器的中心就是图片的中心。

额外验证:明确设置transform-origin

如果还是有问题,可以明确给旋转的元素设置transform-origin(这是默认值,但复杂布局下可能被继承或覆盖),比如在CSS里添加:

.wheel1 img, .wheel2 img {
  transform-origin: center center; /* 等价于50% 50% */
}

这样就能确保旋转中心是元素自身的中心了。

内容的提问来源于stack exchange,提问作者Sami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:32:38