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

如何使用Tailwind CSS实现点击/聚焦红按钮时蓝按钮同步变红

实现方案

你可以用Tailwind自带的peer兄弟节点状态选择器实现这个需求,不需要额外写JS代码,步骤如下:

  • 给红色按钮添加peer类,标记它为状态触发源
  • 给蓝色按钮添加peer-focus:bg-red-400(对应红色按钮聚焦时的样式)、peer-active:bg-red-400(对应红色按钮点击激活时的样式)类即可,如果你需要红色按钮聚焦时蓝色按钮的颜色和红色按钮聚焦色保持一致,把对应类改为peer-focus:bg-red-700即可

完整可运行代码

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

<button class="peer focus:bg-red-700 bg-red-400 font-bold px-4 py-4 rounded-lg">
RED
</button>

<button class="bg-blue-400 peer-focus:bg-red-700 peer-active:bg-red-400 font-bold px-4 py-4 rounded-lg">
BLUE
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:45:03