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

JQuery中TranslateX失效,如何用.animate()替代.css()实现动画?

Fixing jQuery .animate() for translateX Transform Animation

Hey there, let's work through why your current animation isn't firing and get it sorted out:

  • jQuery's native .animate() method doesn't support animating the transform property directly. It’s built to handle simple numeric CSS properties (like width or opacity) and can’t parse compound values like translateX(100%).
  • Also, you had an extra semicolon in 'translateX(100%);' — even if transform was supported, this would break the value parsing.

Solution 1: Use the step Callback (Pure jQuery)

We can animate a custom numeric property and use the step function to update the transform property on every animation frame. This lets us leverage .animate() while working around its limitation with transform:

$(".test").hover(
  // Mouse enter animation
  function() {
    $(this).animate(
      { translatePosition: 100 }, // Custom numeric property to animate
      {
        duration: 1000,
        step: function(now) {
          // Apply the current animation value to translateX
          $(this).css('transform', `translateX(${now}%)`);
        }
      }
    );
  },
  // Mouse leave animation (return to original position)
  function() {
    $(this).animate(
      { translatePosition: 0 },
      {
        duration: 1000,
        step: function(now) {
          $(this).css('transform', `translateX(${now}%)`);
        }
      }
    );
  }
);

Your CSS can stay exactly as it is (no changes needed here):

.test {
  background-color: #f9333c;
  width: 100%;
  height: 100%;
  transform: translateX(0%);
}

How this works:

  • We animate a made-up property translatePosition from 0 to 100 (and back to 0 when the mouse leaves).
  • The step callback runs on every frame of the animation, taking the current value (now) and applying it to the transform: translateX() property. This creates the smooth, animated transition you’re after.

Alternative: CSS Transitions (Simpler, More Performant)

If you don’t strictly need to use jQuery’s .animate(), CSS transitions are a cleaner way to achieve this effect. Just add a transition rule to your CSS:

.test {
  background-color: #f9333c;
  width: 100%;
  height: 100%;
  transform: translateX(0%);
  transition: transform 1000ms ease; /* Add transition rule */
}

.test:hover {
  transform: translateX(100%);
}

With this approach, you don’t need any jQuery code at all — the browser handles the animation natively, which is also more efficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:53:07