【问题标题】:How can i toggle between dark/light mode using a div? [closed]如何使用 div 在暗/亮模式之间切换? [关闭]
【发布时间】:2020-10-09 09:40:53
【问题描述】:

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

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

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

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

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

我尝试了 JS,但无法让它工作。任何人都可以在正确的方向上给我建议吗?

【问题讨论】:

  • 我建议您通过 Google 或搜索 SO 做一些additional research,然后返回您的代码并解释您的尝试。
  • 请附上您的 JS 代码以方便获取帮助。

标签: javascript html css toggle


【解决方案1】:

如果不想为此添加&lt;script&gt; 标签,可以直接在onclick 事件上定义:

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

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

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

但是如果你的页面有多个这个元素的实例,你应该正确注册它们:

[...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>

【讨论】:

  • 您好,感谢您的精彩回答!当我这样做时,它只会将按钮切换为黑暗,而不是每个“主题”标签。有什么建议吗?
猜你喜欢
  • 2021-09-12
  • 2020-08-24
  • 1970-01-01
  • 2021-05-30
  • 2021-03-05
  • 2020-10-20
  • 1970-01-01
  • 2020-10-01
  • 2022-01-10
相关资源
最近更新 更多