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

如何用单按钮实现JavaScript计算器三次样式切换(含初始还原)

实现三次样式循环切换的方案

核心思路是通过状态变量追踪当前样式索引,结合取模运算实现循环切换,再通过给根元素切换CSS类来应用不同样式。

1. 定义三种样式的CSS类

/* 初始默认样式 */
.default {
  background-color: #ffffff;
  color: #333333;
}

/* 第一种切换样式 */
.theme1 {
  background-color: #2c3e50;
  color: #ecf0f1;
}

/* 第二种切换样式 */
.theme2 {
  background-color: #f39c12;
  color: #2c3e50;
}

/* 可选:给计算器容器加基础样式,让切换效果更直观 */
.calculator {
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  margin: 20px auto;
}

2. HTML结构

<div class="calculator default">
  <div class="display">0</div>
  <button id="themeToggle">切换样式</button>
  <!-- 其他计算器功能按钮... -->
</div>

3. JavaScript逻辑

const themeToggleBtn = document.getElementById('themeToggle');
const targetElement = document.querySelector('.calculator'); // 若要全局切换,换成document.body或document.documentElement

// 按顺序定义样式类,对应初始→样式1→样式2
const themes = ['default', 'theme1', 'theme2'];
let currentThemeIndex = 0; // 初始对应default

themeToggleBtn.addEventListener('click', () => {
  // 索引递增后取模3,实现0→1→2→0的循环
  currentThemeIndex = (currentThemeIndex + 1) % 3;
  
  // 清除所有样式类,再添加当前索引对应的类
  targetElement.classList.remove(...themes);
  targetElement.classList.add(themes[currentThemeIndex]);
});

关键细节说明

  • 用(currentThemeIndex + 1) % 3确保索引始终在0、1、2之间循环,第三次点击自动回到初始样式。
  • 通过classList.remove(...themes)一次性移除所有样式类,避免多个类叠加导致样式冲突。
  • 如果要给整个项目切换样式,把targetElement换成document.body或document.documentElement(HTML根元素)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:19:53