如何实现点击切换时为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
相关产品推荐
相关产品推荐

