通过属性选择器实现主题切换(原生极简版)

85 阅读1分钟

实现原理

root元素里面写主题配套变量,再通过属性去区分不同主题,想切换的时候用js给html元素切换属性即可。

代码效果

theme.gif

完整代码实现

<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    :root[data-theme='dark'] {
      --color: yellow;
      --background-color: red;
    }
    :root[data-theme='light'] {
      --color: blue;
      --background-color: aliceblue;
    }
    .box {
      color: var(--color);
      background-color: var(--background-color);
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="box">
    这是文字
  </div>
  <button onclick="setTheme('light')">切换白天主题</button>
  <button onclick="setTheme('dark')">切换黑暗主题</button>
  <script>
    const bodyElement = document.querySelector('html');
    function setTheme(themeValue) {
      bodyElement.setAttribute('data-theme', themeValue);
    }
  </script>
</body>
</html>