首页 > 编程技术 > js

详解web如何改变主题配色方法示例

发布时间:2023-3-7 15:03 作者:今天又学到了

正文

自从苹果系统支持了暗色主题之后,越来越多的网站开始支持暗色模式,来改善用户夜晚使用网站的舒适度,那么一般都是如何处理的呢.

在开始一个项目时,我们通常会将用到的主题色,和一些全局配置,通过css变量定义在根元素,注意,变量必须以"--"开头

:root {
  --color-primary: white;
}

以下是可以改变主题的几种方式

一、通过在根元素定义选择器来改变主题

定义class

html.dark {
  --docsearch-modal-background: #23272f;
  --docsearch-hit-background: #23272f;
  --docsearch-highlight-color: #149eca;
}

<html class="dark"></html>

定义dateset

:root[data-theme='dark'] { 
    --color-primary: #3C7EFF; 
}

<html date-theme='dark'></html>

// 设置页面根元素的 dataset
const doc = document.documentElement; 
const newTheme = theme === 'light' ? 'dark' : 'light'; 
doc.dataset.theme = newTheme;

自定义标签属性

:root[arco-theme='dark'] { 
    --color-primary: #3C7EFF; 
}

<html arco-theme='dark'></html>

// 设置页面根元素的 dataset
const [theme, setTheme] = useStorage('arco-theme', 'light');
const doc = document.documentElement; 
doc.setAttribute('arco-theme', 'dark');

样式一般定义在:root中,当然也可以定义在html、body标签中,目的是为了能够在全局使用

二、通过prefers-color-scheme来改变主题

通过媒体查询,获取系统主题,来改变网站主题. scheme有三个可选值,分别是light、dark 和 no-preference,代表着亮色主题、暗色主题和未知,大部分浏览器都支持该特性,可以在这里查看 caniuse.

:root {
      --font-color: black;
}
  
@media (prefers-color-scheme: dark) {
  :root {
      --font-color: white;
  }
}

获取主题色

const theme = window.matchMedia('(prefers-color-scheme: dark)');
if (theme.matches) { } else { }

通过通知,监听主题色的变化

// handleChange(event) { if (event.matches) {} else {} }
const theme = window.matchMedia('(prefers-color-scheme: dark)');
theme.addListener(handleChange);
theme.removeListener(handleChange);

三、通过颜色反转来改变主题

这种filter方式,就是所谓的一行代码改变主题的方式,加入如下代码即可,不过这种一刀切的方式不够灵活,有些元素不需要颜色反转,还需要再加一层hue-rotate(180deg)反转回来,不推荐使用.

// 颜色反转,色调反转
filter: invert(1) hue-rotate(180deg);

特殊纪念日,网站置灰,也是用filter来实现的

filter: grayscale(1);

总结

以上就是三种改变主题的方法,不过通常我们做法是使用dateset + media(prefers-color-scheme)结合的方式来处理. 优先使用dateset,如果用户没有设置dateset,就使用media来获取系统主题,然后设置即可,更多关于web改变主题配色的资料请关注猪先飞其它相关文章!

原文出处:https://juejin.cn/post/7206701761683685434

标签:[!--infotagslink--]

您可能感兴趣的文章: