CSS 多主题切换思路

前言

本篇仅提供多主题切换思路,示例简单且清晰。

实现

步骤一:多主题(颜色)定义

  • 定义根伪类 :root,代码第 2 和 7 行。分别定义了默认和带参数的伪类;
  • 定义 CSS 变量,注意变量名需要以两个减号(--)开始;
  • 注意此处仅设置了两个主题,多主题同理;
/* 默认 */
:root {
   
    --box-bg-01: yellow;
    --box-bg-02: blue;
}
/* 带参数 myTheme02 */
:root[my-theme=myTheme02] {
   
    --box-bg-01: red;
    --box-bg-02: green;
}

步骤二:主题切换

  • 直接控制 html 根节点;
changeTheme() {
   
    let type = document.documentElement.getAttribute('my-theme')==='myTheme02' ? '' : 'myTheme02';
    document.documentElement.setAttribute('my-theme', type);
}

默认主题:可看到下图右侧 html 标签上无其它属性。样式 root 中有可查看CSS变量。
在这里插入图片描述

带参主题 myTheme02:可看到下图右侧 html 标签上有属性my-theme样式 root 中有可查看CSS变量。

在这里插入图片描述

效果

在这里插入图片描述

完整代码

  • 代码 19 - 30 行,注意 :root 定义在全局样式中;
<template>
    <div>
        <div><button @click="changeTheme">主题切换</button></div>
        <div class="box box01"></div>
        <div class="box box02"></div>
    </div>
</template>

<script>
export default {
    methods: {
        changeTheme() {
            let type = document.documentElement.getAttribute('my-theme')==='myTheme02' ? '' : 'myTheme02';
            document.documentElement.setAttribute('my-theme', type);
        }
    }
}
</script>
<style>
/* 默认 */
:root {
    --box-bg-01: yellow;
    --box-bg-02: blue;
}
/* 带参数的 */
:root[my-theme=myTheme02] {
    --box-bg-01: red;
    --box-bg-02: green;
}
</style>
<style lang="stylus" scoped>
.box {
    display: inline-block;
    width: 100px;
    height: 100px;
}
.box01 {
    background: var(--box-bg-01);
}
.box02 {
    background: var(--box-bg-02);
}
</style>

相关推荐

  1. CSS_scss切换主题

    2023-12-08 20:26:02       29 阅读
  2. css前端主题切换方案(三种)

    2023-12-08 20:26:02       49 阅读
  3. 主题切换CSS文件篇

    2023-12-08 20:26:02       25 阅读
  4. 主题切换之根元素CSS自定义类

    2023-12-08 20:26:02       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-08 20:26:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-08 20:26:02       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-08 20:26:02       82 阅读
  4. Python语言-面向对象

    2023-12-08 20:26:02       91 阅读

热门阅读

  1. Connection reset

    2023-12-08 20:26:02       51 阅读
  2. Flask 最佳实践(一)

    2023-12-08 20:26:02       48 阅读
  3. 解释区块链技术的应用场景和优势。

    2023-12-08 20:26:02       60 阅读
  4. LeetCode //C - 188. Best Time to Buy and Sell Stock IV

    2023-12-08 20:26:02       56 阅读
  5. 初识 OpenCV

    2023-12-08 20:26:02       64 阅读