likes
comments
collection
share

Web前端主题切换的几种方案

作者站长头像
站长
· 阅读数 39

欢迎关注我的公众号睿Talk,获取我最新的文章:Web前端主题切换的几种方案

一、前言

本文将介绍 Web 前端主题切换的几种常用方案,示例代码基于 React 框架。废话少说,show you the code!

二、场景一:预定义主题

这种场景比较常见的情况是预定义浅色和深色 2 个主题,可以有 2 种实现方案。

方案1:CSS 属性覆盖

这种方案利用了css多层样式精确匹配的特点,通过样式覆盖的方式实现主题的切换。首先需要在应用的根元素中设一个 class,切换主题时给 class 赋上对应的值,下面以theme1/theme2为例。

h2 {
  color: brown;
}
button {
  background-color: yellow;
}
.theme2 h2 {
  color: blue;
}
.theme2 button {
  background-color: green;
}
import './combine.css';
export default function App() {
  const [theme, setTheme] = useState('theme1');
  return (
    // 切换应用根元素的 class
    <div className={theme}>
      <h2>{theme}</h2>
      <button onClick={() => {
        setTheme(theme => { if (theme === 'theme1') return 'theme2'; return 'theme1' })
      }}>切换主题</button>
    </div>
  );
}

方案2:css变量替换

这个方案跟方案一的思路是相似的,区别是使用了 css变量 来定义主题色。首先要在页面的根元素上定义一个 dataset: <html lang="en" data-theme="theme1">。然后定义不同主题的变量值:

<style id="theme-var">
  :root {
        --font-color: brown;
        --button-color: yellow;
      }
  :root[data-theme=theme2] {
    --font-color: blue;
    --button-color: green;
  } 
</style>
h2 {
  color: var(--font-color, black)
}
button {
  background-color: var(--button-color, gray);
}
import './var.css';
export default function App() {
  const [theme, setTheme] = useState('theme1');
  return (
    <div>
      <h2>{theme}</h2>
      <button onClick={() => {
        const doc = document.documentElement;
        const newTheme = theme === 'theme1' ? 'theme2' : 'theme1';
        // 设置页面根元素的 dataset
        doc.dataset.theme = newTheme;
        setTheme(newTheme);
      }}>切换主题</button>
    </div>
  );
}

三、场景二:允许用户自定义主题

这种场景与场景一的最大区别是无法预定义 CSS 属性和变量,一般是要搭配接口来实现动态替换的功能。下面的例子只演示原理,忽略接口数据的处理。

方案1:全量替换CSS

这个方案比较简单粗暴,需要将页面的所有 css 打包在一起,放在预定义好 ID 的 style 标签中,切换主题的时候将 css 全量替换掉。

// 假设下面的 css 是从接口获取的字符串
const themeAll1 = 'h2 {color: brown;} button {background-color: yellow;}'
const themeAll2 = 'h2 {color: blue;} button {background-color: green;}'
export default function App() {
  const [theme, setTheme] = useState('主题1');
  return (
    <div>
      <h2>{theme}</h2>
      <button onClick={() => {
        // 替换 style 标签的内容
        if (theme === '主题1') {
          document.getElementById('theme-all').innerText = themeAll2;
          setTheme('主题2')
        } else {
          document.getElementById('theme-all').innerText = themeAll1;
          setTheme('主题1')
        }

      }}>切换主题</button>
    </div>
  );
}

方案2:CSS变量替换

方案一比较简单粗暴,数据量也比较大。可以使用 css变量 来进行优化,抽取主题色变量,放在根伪类下面。切换主题时只需要动态设置 style 标签内 css 变量的值。

<style id="theme-var">
  :root {
    --font-color: brown;
    --button-color: yellow;
  }
</style>
h2 {
  color: var(--font-color, black)
}
button {
  background-color: var(--button-color, gray);
}
import './var.css';
// 假设下面的 css 是从接口获取的字符串
const themeVar1 = ':root {--font-color: brown; --button-color: yellow;}'
const themeVar2 = ':root {--font-color: blue; --button-color: green;}'
export default function App() {
  const [theme, setTheme] = useState('主题1');
  return (
    <div>
      <h2>{theme}</h2>
      <button onClick={() => {
        // 替换 style 标签的内容
        if (theme === '主题1') {
          document.getElementById('theme-var').innerText = themeVar2;
          setTheme('主题2')
        } else {
          document.getElementById('theme-var').innerText = themeVar1;
          setTheme('主题1')
        }
      }}>切换主题</button>
    </div>
  );
}

六、总结

本文介绍了 4 种常用的主题切换方案,当中最后一个方案最灵活,可以配合 API 扩展无限量的主题。对于更常见的浅色加深色主题模式,可以选择第 2 种方案。他们的共同点都是使用了 css 变量抽取主题颜色,实现起来非常优雅。

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/dev...