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

如何实现点击切换时为html标签循环切换两类样式类的功能

类循环切换功能修改方案

修改后的JavaScript代码

const html = document.querySelector('html');
const button = document.querySelector('.contrast__link');

button.addEventListener('click', e => {
  e.preventDefault();
  
  if (!html.classList.length) {
    // 默认无类状态,添加dark-mode类
    html.classList.add('dark-mode');
  } else if (html.classList.contains('dark-mode')) {
    // 当前为dark-mode,切换到new-mode
    html.classList.remove('dark-mode');
    html.classList.add('new-mode');
  } else if (html.classList.contains('new-mode')) {
    // 当前为new-mode,移除类回到默认状态
    html.classList.remove('new-mode');
  }
});

逻辑说明

  • 页面加载时HTML标签无类,第一次点击直接添加dark-mode类
  • 第二次点击时检测到dark-mode类,移除它并添加new-mode类
  • 第三次点击时检测到new-mode类,移除该类回到初始无类状态
  • 后续点击重复上述循环逻辑

原有CSS和HTML代码无需修改

CSS代码

html { background: white; color: black; }
.dark-mode { background: black; color: white;}
.new-mode { background: blue; color: white;}

HTML代码

<p class="contrast__link">Click here</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:55:25