這篇文章給大家分享的是有關怎么簡單實現CSS主題的切換的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
創新互聯成立于2013年,我們提供高端成都網站建設、成都網站制作公司、成都網站設計、網站定制、成都全網營銷、成都小程序開發、微信公眾號開發、營銷推廣服務,提供專業營銷思路、內容策劃、視覺設計、程序開發來完成項目落地,為木托盤企業提供源源不斷的流量和訂單咨詢。

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主題的切換
文章鏈接:http://www.yijiale78.com/article28/pcsejp.html
成都網站建設公司_創新互聯,為您提供網站改版、自適應網站、虛擬主機、Google、品牌網站設計、App開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯