【问题标题】:why doesn't JavaScript work with dark mode?为什么 JavaScript 不能在暗模式下工作?
【发布时间】:2021-12-31 01:46:05
【问题描述】:

我希望当你点击它时,暗模式按钮变成 css,在等待模式下按钮是暗的,而在暗模式下按钮是亮的!

var toggleButton = document.getElementById('mode-toggle')
var isDarkMode = false;

function myFunction() {
  isDarkMode = !isDarkMode;
  document.querySelectorAll('div.scrollseite,div.scrollseite2').forEach(e => e.classList.toggle('dark-mode'))
  document.querySelectorAll('div.btndarkmode').forEach(e => e.classList.toggle('btnwhitemode'))
  toggleButton.innerHTML = isDarkMode ? 'Light mode' : 'Dark mode'
}
.btndarkmode {
  background-color: #36393F;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btndarkmode:hover {
  background-color: #32353B;
  color: gray;
}

.btnwhitemode {
  background-color: white;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btnwhitemode:hover {
  background-color: white;
  color: gray;
}

.dark-mode {
  background-color: #36393F !important;
  color: white !important;
}
<button onclick="myFunction()" class="btndarkmode" id="mode-toggle">Dark mode</button>

【问题讨论】:

  • 如果它说字数少于代码,你不必添加额外的字符,忽略它并按post。
  • 因为你使用了div.scrollseite,div.scrollseite2,剩下的HTML在哪里?
  • 哥们没有div.btndarkmode,应该是button.btndarkmode

标签: javascript html css themes darkmode


【解决方案1】:

我在代码中添加了 cmets。代码是不言自明的,我只是检查按钮是处于暗模式还是亮模式。如果是深色模式,则将文本内容更改为浅色模式和背景色,反之亦然

var toggleButton = document.getElementById('mode-toggle')

function myFunction() {
  // To Check if element is in Darkmode
  if(toggleButton.textContent === "Dark mode") {
    toggleButton.textContent = "Light mode"
    toggleButton.style.background = "#eee"
  return
  }
  
  // To Check if element is in Lightmode
   if(toggleButton.textContent === "Light mode") {
     toggleButton.textContent = "Dark mode"
     toggleButton.style.background = "#333"
   return
   }
}
.btndarkmode {
  background-color: #36393F;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btndarkmode:hover {
  background-color: #32353B;
  color: gray;
}

.btnwhitemode {
  background-color: white;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btnwhitemode:hover {
  background-color: white;
  color: gray;
}

.dark-mode {
  background-color: #36393F !important;
  color: white !important;
}
<button onclick="myFunction()" class="btndarkmode" id="mode-toggle">Dark mode</button>

【讨论】:

  • 在没有任何解释的情况下写答案并没有多大帮助。您应该解释哪些部分很重要以及为什么。
  • 我在代码中添加了cmets。代码是不言自明的,我只是检查按钮是处于暗模式还是亮模式。如果是深色模式,请将文本内容更改为浅色模式和背景色,反之亦然
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多