资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

怎么简单实现CSS主题的切换

这篇文章给大家分享的是有关怎么简单实现CSS主题的切换的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

创新互联成立于2013年,我们提供高端成都网站建设成都网站制作公司成都网站设计、网站定制、成都全网营销成都小程序开发、微信公众号开发、营销推广服务,提供专业营销思路、内容策划、视觉设计、程序开发来完成项目落地,为木托盘企业提供源源不断的流量和订单咨询。

怎么简单实现CSS主题的切换

HTML

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


    
    
    

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

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主题的切换
本文网址:http://cdkjz.cn/article/pcsejp.html
返回首页 了解更多建站资讯
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220