详解如何简单实现CSS主题的切换

发布时间:2022-04-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了详解如何简单实现CSS主题的切换脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

我最近在我的个人网站上添加了一个非常简单的配色方案(主题)切换器。您可以在网站的页脚中切换此简单的颜色切换器,以查看其实际效果。万一其他人希望将这样的功能添加到自己的站点/项目中,我想我会写一篇简短的文章解释如何做。让我们开始吧。

HTML

首先,我们需要包含“按钮”,这些按钮将触发主题根据选择的主题进行切换。(注:你总是可以使这些作为 options 一个 select 元素,如果你最好的方法)

<div class="color-select">
    <button onclick="toggleDefaultTheme()"></button>
    <button onclick="toggleSecondTheme()"></button>
    <button onclick="toggleThirdTheme()"></button>
</div>

而已!现在不必太担心 onclick 参数,我们将在添加JavaScript时再回到这一点。剩下的唯一一项是向 html 元素添加默认主题类,如下所示:

<html class="theme-default">

CSS

接下来,我们需要为两个 color-select 按钮设置样式,并使用将更改整个网站的自定义配色方案。我们将从配色方案开始。

为了使这些主题之间能够无缝切换,我们将更改的颜色集设置为CSS变量

.theme-default {
   --accent-color: #72F1b8;
   --font-color: #34294f;
}

.theme-second {
    --accent-color: #FFBF00;
    --font-color: #59316B;
}

.theme-third {
    --accent-color: #d9455f;
    --font-color: #303960;
}

body {
    background-color: VAR(--accent-color);
    color: var(--font-color);
}

最后,我们设置面向用户的色板的样式:

.color-select button {
    -moz-apPEarance: none;
    appearance: none;
    border: 2px solid;
    border-radius: 9999px;
    cursor: pointer;
    height: 20px;
    margin: 0 0.8rem 0.8rem 0;
    outline: 0;
    width: 20px;
}

/* Style each swatch to match the corresponding theme */
.color-select button:nth-child(1) { background: #72f1b8; border-color: #34294f; }
.color-select button:nth-child(2) { background: #FFBF00; border-color: #59316B; }
.color-select button:nth-child(3) { background: #d9455f; border-color: #303960; }

JavaScript

我们需要使每个色样按钮触发其相应的主题,并交换出 theme-default 我们最初附加到主 html 元素上的类。我们还需要存储用户选择的内容 localStorage ,因此在重新加载或导航到其他页面时,他们的选择仍然存在。

// Set a given theme/color-scheme
function setTheme(themeName) {
    localStorage.setITem('theme', themeName);
    document.documentElement.classname = themeName;
}

// Toggle between color themes
function toggleDefaultTheme() {
    if (localStorage.getItem('theme') !== 'theme-default'){
        setTheme('theme-default');
    }
}
function toggleSecondTheme() {
    if (localStorage.getItem('theme') !== 'theme-second'){
        setTheme('theme-second');
    }
}
function toggleThirdTheme() {
    if (localStorage.getItem('theme') !== 'theme-third'){
        setTheme('theme-third');
    }
}

// Immediately set the theme on initial load
(function () {
    if (localStorage.getItem('theme') === 'theme-default') {
        setTheme('theme-default');
    }
    if (localStorage.getItem('theme') === 'theme-second') {
        setTheme('theme-second');
    }
    if (localStorage.getItem('theme') === 'theme-third') {
        setTheme('theme-third');
    }
})();

就是这样!现在,这仅取决于您希望每种主题样式的自定义程度。可能性是无止境!

到此这篇关于详解如何简单实现CSS主题的切换的文章就介绍到这了,更多相关CSS主题的切换内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的详解如何简单实现CSS主题的切换全部内容,希望文章能够帮你解决详解如何简单实现CSS主题的切换所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:CSSCSS