当前位置:首页 > 编程笔记 > 正文
已解决

CSS 多主题切换思路

来自网友在路上 11478147提问 提问时间:2023-12-02 21:31:27阅读次数: 147

最佳答案 问答题库1478位专家为你答疑解惑

前言

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

实现

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

  • 定义根伪类 :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>
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"CSS 多主题切换思路":http://eshow365.cn/6-42217-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!