javascript 如何根据用户的时间将lite模式更改为dark模式?

1l5u6lss  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(121)

如何根据用户使用JS的时间将lite模式更改为dark模式?'

// function to set a given theme/color-scheme
  function setTheme(themeName) {
     localStorage.setItem('theme', themeName);
     document.documentElement.className = themeName;
}
// function to toggle between light and dark theme
function toggleTheme() {
  if (localStorage.getItem('theme') === 'theme-dark') {
     setTheme('theme-light');
  } else {
     setTheme('theme-dark');
  }
}
// Immediately invoked function to set the theme on initial load
(function () {
  if (localStorage.getItem('theme') === 'theme-dark') {
     setTheme('theme-dark');
     document.getElementById('dark-light-mode').checked = false;
 } else {
     setTheme('theme-light');
     document.getElementById('dark-light-mode').checked = true;
 }
})();

'
'

<label id="switch" class="switch">
     <input type="checkbox" onchange="toggleTheme()" id="dark-light-mode">
     <span class="slider round"></span>
   </label>

'
我想通过用户的时间在亮和暗之间改变主题

abithluo

abithluo1#

使用Date对象并根据选定的时间应用主题
你可以做这样的事。

let hour = (new Date).getHours();

  if (hour >= 18) {
     setTheme('theme-dark');
  } else {
     setTheme('theme-light');
  }

如果时间大于18,则应用黑暗主题
您还需要setInterval,这样它将根据条件监视时间和触发事件。

相关问题