实现网站黑暗模式

1.CSS媒体查询,根据系统自动切换不同样式

//还可以配合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>    

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

<style>
      body {
          background:#fff
      }

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

通过事件触发,切换样式

<head>
    <link href="light.css" id="theme" />
</head>
<body>
    <button id="btn">切换</button>

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

3.使用CSS filter

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

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

filter其实是滤镜,invert()作用是反转颜色通道数值,接收的值在 01;hue-rotate() 的作用是转动色盘,接收的值在 0deg360deg。

https://developer.mozilla.org/en-US/docs/Web/CSS/filter

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

html img {
        filter: invert(1) hue-rotate(180deg);
      }

如果对产品要求高,可以使用样式切换的方式,因为filter算法会出现某些颜色不是你希望的滤镜效果,不容易调节

posted @   7c89  阅读(54)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示