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

如何在按钮禁用时关闭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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:10:03