如何在按钮禁用时关闭framer-motion的whileHover效果?
实现方法
当然可以实现。你只需要根据按钮的禁用状态条件性地设置 whileHover 属性即可:当按钮处于禁用状态时,将 whileHover 设置为 null 或 undefined,Framer Motion 就不会触发悬停动画了。
修改后的代码示例:
<div className="flex space-x-5"> <motion.button whileHover={(!stock || count <= 1) ? null : { scale: 1.1 }} transition={{ type: "spring", stiffness: 100, duration: 0.2 }} onClick={decrement} className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white" disabled={!stock || count <= 1} > - </motion.button> <span>{count}</span> <motion.button whileHover={!stock ? null : { scale: 1.1 }} transition={{ type: "spring", stiffness: 100, duration: 0.2 }} onClick={increment} className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white" disabled={!stock} > + </motion.button> </div>
原理说明:
- 当按钮的
disabled条件成立时,whileHover被设为null,Framer Motion 会跳过悬停动画的应用。 - 当按钮可用时,
whileHover恢复为原来的缩放动画配置,正常触发悬停效果。
这样既保留了禁用状态下的样式(比如透明度变化、光标样式),又关闭了不需要的悬停动画。
内容的提问来源于stack exchange,提问作者Andrés Marino
相关产品推荐
相关产品推荐

