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 thetransformproperty directly. It’s built to handle simple numeric CSS properties (likewidthoropacity) and can’t parse compound values liketranslateX(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
translatePositionfrom 0 to 100 (and back to 0 when the mouse leaves). - The
stepcallback runs on every frame of the animation, taking the current value (now) and applying it to thetransform: 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
相关产品推荐
相关产品推荐

