前端中有用到需要設(shè)置主題顏色抛寝,根據(jù)用戶喜歡實(shí)現(xiàn)換膚的可以使用css中:root定義變量的方式,或者使用動(dòng)態(tài)切換引入的外部css樣式表實(shí)現(xiàn)沐兵,這里著重記錄下動(dòng)態(tài)修改css中:root定義的變量實(shí)現(xiàn)換膚:
創(chuàng)建variable.scss别垮,定義顏色變量:
:root {
--light: red;
--dark: black;
}
這里定義變量必須是以'--'開頭,然后其他頁面的樣式表就可以直接引用這個(gè)變量了
引用variable中定義的變量:
.title{
font-size: 20px;
color: var(--light);
}
動(dòng)態(tài)修改:root變量中的值:
document.documentElement.style.setProperty(`--light`, 'red');
至此就完成了動(dòng)態(tài)修改:root變量實(shí)現(xiàn)換膚了扎谎,具體的應(yīng)用場景中我們應(yīng)該是在頁面上操作碳想,選中需要的膚色然后修改:root定義的變量值,考慮到瀏覽器刷新會(huì)重置原始狀態(tài)的值毁靶,這里要結(jié)合本地存儲(chǔ)方式記住選中的膚色胧奔,具體的實(shí)現(xiàn)參考:
const title = document.getElementsByClassName("title")[0]
title.onclick = function() {
document.documentElement.style.setProperty(`--light`, 'blue');
window.localStorage.setItem('style', 'blue')
}
window.onload = function() {
const style = window.localStorage.getItem('style')
if(style) {
document.documentElement.style.setProperty(`--light`, style);
}else {
document.documentElement.style.setProperty(`--light`, 'red');
}
}