首页 > 解决方案 > 使用深色或浅色模式

问题描述

将此类内容合并到我的网站的最佳方法是什么?我试过使用插件,但我无法让它工作。不一定要花哨。

有没有人有它或过去使用过他们可以推荐的一个?否则,有没有办法使用 JavaScript 对其进行编码?

标签: javascript

解决方案


也许这应该可以帮助您启动。

<html class="theme-light">
  <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }

    .theme-light {
      --color-primary: #0060df;
      --color-secondary: #fbfbfe;
      --color-accent: #fd6f53;
      --font-color: #000000;
    }

    .theme-dark {
      --color-primary: #17ed90;
      --color-secondary: #243133;
      --color-accent: #12cdea;
      --font-color: #ffffff;
    }

    .container {
      display: flex;
      width: 100%;
      height: 100%;
      background: var(--color-secondary);
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .container h1 {
      color: var(--font-color);
    }

    .container button {
      color: var(--font-color);
      background: var(--color-primary);
      padding: 10px 20px;
      border: 0;
      border-radius: 5px;
    }
  </style>

  <script>
    // Set a Theme
    function setTheme(themeName) {
      localStorage.setItem('theme', themeName);
      document.documentElement.className = themeName;
    }

    // Toggle From light and dark theme and Vice-Versa
    function toggleTheme() {
      if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-light');
      } else {
        setTheme('theme-dark');
      }
    }

    // Onload Theme
    (function() {
      if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-dark');
      } else {
        setTheme('theme-light');
      }
    })();
  </script>

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

</html>

推荐阅读