当前位置: 首页 > article >正文

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>

http://www.kler.cn/a/153500.html

相关文章:

  • Redis主从复制实现RCE
  • IP地理定位技术的服务内容详解
  • Python发送微信模板消息
  • 一、Oceanbase基础
  • 【STM32】EXTI外部中断
  • 电子学会C/C++编程等级考试2021年06月(四级)真题解析
  • Vmware安装Centos7
  • flutter开发实战-ValueListenableBuilder实现局部刷新功能
  • vue给table组件添加合计
  • FO-like Transformation in QROM Oracle Cloning
  • 100.有序数组的平方(力扣)
  • nrm : 镜像源工具npm镜像切换
  • MVCC是如何保证隔离性的
  • TA-Lib学习研究笔记(八)——Momentum Indicators 上
  • 企业存货库存综合分析全流程图
  • ElasticSearch之Force merge API
  • Vue 3.0 响应式 计算和侦听
  • Elasticsearch 优化查询中获取字段内容的方式,性能提升5倍!
  • 全志XR806基于FreeRTOS下部署竞技机器人先进模糊控制器
  • 将本地项目推送到github