Как переключаться между светлым и темным режимами с помощью water.css

#javascript #html #css

#javascript #HTML #css

Вопрос:

Я использую water.css на своем веб-сайте, и у меня есть этот js-код:

 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');
   } else {
      setTheme('theme-light');
   }
})();
  

и эта кнопка для переключения:

 <div class="container">
        <h1>Theme Switcher</h1>
        <button id="switch" onclick="toggleTheme()">Switch</button>
    </div>
  

Я импортирую файл javascript и хотел бы знать, как я могу изменить код javascript для переключения между двумя ссылками cdn:

  1. dark.min.css

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">

и 2. water.css

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css">

Ответ №1:

Вот как вы можете изменить тему:

HTML

 <!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>

  <body>
    <div class="container">
      <h1>Theme Switcher</h1>
      <button id="switch" onclick="toggleTheme()">Switch</button>
    </div>
  </body>

</html>
  

javacript

 function setTheme(themeName) {
  localStorage.setItem('theme', themeName);

  //document.documentElement.className = themeName;

  var link = document.createElement('link');
  link.rel = 'stylesheet';
  if (themeName == "theme-dark") {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
  } else {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
  }
  document.head.appendChild(link);
}

// 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');
  } else {
    setTheme('theme-light');
  }
})();

  

Изменения, которые я внес, находятся в setTheme функции:

 var link = document.createElement('link');
  link.rel = 'stylesheet';
  if (themeName == "theme-dark") {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
  } else {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
  }
  document.head.appendChild(link);
  

Это добавит соответствующий css на основе вашей темы.

Вот демонстрационная версия JSFiddle live.

Комментарии:

1. тема не сохраняется, когда пользователь нажимает кнопку «Назад».

2. @Liel Я протестировал это, и это действительно сохраняет тему, должно быть, какая-то другая проблема.