如何使用div在暗/亮模式之间切换?

时间:2020-10-09 09:40:53

标签: javascript html css toggle

我想使用div切换暗/亮模式。

<div theme="light" class="page login">

theme = light应该在单击div时切换为“暗”或“亮”。

<div theme="light" id="switch-theme" class="switch-btn">

这是单击时应在两种模式之间切换的div。

我尝试了JS,但无法正常工作。有人可以向我建议正确的方向吗?

1 个答案:

答案 0 :(得分:1)

如果您不想为此添加<script>标记,则可以直接在onclick事件上定义此标记:

this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark');

[theme='light'] {
  background-color: white;
  color: black;
}

[theme='dark'] {
  background-color: black;
  color: white;
}
<div theme="light" id="switch-theme" class="switch-btn" onclick="this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark')">Lorum Ipsum</div>

但是,如果您的页面上有此元素的多个实例,则应正确注册它们:

[...document.querySelectorAll('[theme]')].forEach(e => e.addEventListener('click', switchTheme));

function switchTheme() {
  this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark');
}
[theme='light'] {
  background-color: white;
  color: black;
}

[theme='dark'] {
  background-color: black;
  color: white;
}
<div theme="light" id="switch-theme" class="switch-btn">Lorum Ipsum</div>
<div theme="light" id="switch-theme" class="switch-btn">Lorum Ipsum</div>
<div theme="light" id="switch-theme" class="switch-btn">Lorum Ipsum</div>