如何实现网站黑暗模式

891 阅读1分钟

背景

互联网行业从业者,很多人喜欢在深夜工作,为此很多网站也做了夜间浏览模式,下面提供几种实现方式。

探索

  1. 使用CSS媒体查询,根据系统自动切换不同样式
    <style>
        @media (prefers-color-scheme: dark) {
          body {
            color: #eee;
            background: #121212;
          }
          body a {
            color: #809fff;
          }
        }
  
        @media (prefers-color-scheme: light) {
          body {
            color: #222;
            background: #fff;
          }
          body a {
            color: #0033cc;
          }
        }
      </style>
    <p>hello world</p>

  1. 使用JS判断,根据系统自动切换类名控制样式

    <style>
      body {
        --text-color: #222;
        --bkg-color: #fff;
        --anchor-color: #0033cc;
      }

      body.dark-theme {
        --text-color: #eee;
        --bkg-color: #121212;
        --anchor-color: #809fff;
      }

      body {
        color: var(--text-color);
        background: var(--bkg-color);
      }

      body a {
        color: var(--anchor-color);
      }
    </style>

    <script>
      if (
        window.matchMedia &&
        window.matchMedia('(prefers-color-scheme: dark)').matches
      ) {
        document.body.classList.add('dark-theme');
      } else {
        document.body.classList.remove('dark-theme');
      }
    </script>
    <p>hello world</p>

  1. 使用按钮,通过手动点击切换css文件
<head>
    <link href="light-theme.css" rel="stylesheet" id="theme_link" />
</head>
<body>
    <button id="btn">切换</button>

    <script>
      const btn = document.querySelector('#btn');
      const themeLink = document.querySelector('#theme_link');
      btn.addEventListener('click', function () {
        if (themeLink.getAttribute('href') == 'light-theme.css') {
          themeLink.href = 'dark-theme.css';
        } else {
          themeLink.href = 'light-theme.css';
        }
      });
    </script>
</body>


使用CSS filter实现

<style>
    html {
        background: #fff;
        filter: invert(1) hue-rotate(180deg);
    }
</style>

<p>hello world</p>

注意:html上必须要设置背景色,不然filter是无效的

filter其实是滤镜,invert()作用是反转颜色通道数值,接收的值在 01;hue-rotate() 的作用是转动色盘,接收的值在 0deg360deg。这两个函数的具体计算方式可以参考MDN CSS filter

filter虽然能够实现黑暗模式,但是有个问题,图片和背景图也会被滤镜,可以通过对图片再filter一次解决这个问题。

 <style>
      html {
        background: #fff;
        filter: invert(1) hue-rotate(180deg);
      }

      html img {
        filter: invert(1) hue-rotate(180deg);
      }
      .box {
        width: 100px;
        height: 100px;
        background-image: url('https://cdn.86886.wang/pic/20220301200132.png');
        background-repeat: no-repeat;
        background-size: 100px 100px;
        filter: invert(1) hue-rotate(180deg);
      }
    </style>

 <img
      src="https://cdn.86886.wang/pic/20220301200132.png"
      width="100px"
      height="100px"
      alt=""
    />
    <p>hello world</p>
    <div class="box"></div>

原图保持不变,只对其他元素滤镜,效果图:

20220301201249

结语

虽然用filter和切换样式这两种方式都能达到目的,如果对产品要求比较高,还是推荐使用样式切换这种方式,毕竟这种方式一切都比较可控。filter算法会出现某些颜色不是你希望的滤镜效果,而自己又不好调整,应为算法比较复杂。