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

如何为多个同class按钮应用classList.toggle实现点击翻转效果

解决多按钮翻转仅第一个生效的问题

问题根源是document.querySelector()只会返回第一个匹配的元素,所以只有第一个按钮能触发翻转。要处理多个按钮,需要用document.querySelectorAll()获取所有目标按钮,然后逐个绑定点击事件,同时让翻转逻辑针对当前被点击的按钮生效。

修改后的完整代码

HTML(示例多个按钮)

<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>
<button class="button reserve" role="button"><i class="bx bx-bell icon"></i>Reserveer</button>

JavaScript

// 获取所有带reserve类的按钮
const buttons = document.querySelectorAll(".reserve");

// 调整翻转函数,接收当前点击的按钮作为参数
function buttonFlip(button) {
  button.classList.toggle("flip");
}

// 遍历每个按钮,绑定点击事件
buttons.forEach(button => {
  button.addEventListener('click', () => {
    buttonFlip(button);
  });
});

CSS(补全样式确保背面内容正常显示)

.button {
  position: relative;
  width: 120px;
  height: 40px;
  transition: all .5s linear;
  transform-style: preserve-3d;
  backface-visibility: hidden;
}

.button::after {
  content: 'X';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotateY(180deg);
  transform-style: preserve-3d;
  backface-visibility: hidden;
  background-color: #f00;
  color: #fff;
}

.flip {
  transform: rotateY(180deg);
}

关键修改说明

  • 获取所有按钮: 用querySelectorAll()替代querySelector(),得到所有匹配.reserve的按钮集合。
  • 翻转函数适配: 让buttonFlip接收按钮元素作为参数,确保操作的是当前点击的按钮,而非固定的单个元素。
  • 遍历绑定事件: 用forEach()遍历按钮集合,给每个按钮单独绑定点击事件,实现点击哪个翻转哪个。
  • CSS补全: 给伪元素添加绝对定位和居中样式,避免和按钮内容重叠;移除过时的-webkit前缀,适配现代浏览器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:05:20