js修改css變數值實現主題切換

jsper發表於2024-11-12

js修改css變數值實現主題切換

                /**
                 * 主題顏色主要包含強調色(比主色更深一點)、主色(文字色)、輔色(比主色淺一點)、淺色、超淺色、灰色、白色,
                 * 前4個顏色依次由深到淺
                 * 強調色、輔色、淺色、超淺色透過主色調整顏色深度計算得出。
                 */

                // 主色
                const themePrimaryColor = decodeURIComponent(getUrlParam('themeColor')) // #005BFF, #00aa00 #409eff
                const themeBackgroundImage = decodeURIComponent(getUrlParam('themeBackgroundImage')) // #005BFF, #00aa00 #409eff

                const rgbaObject = hex2RgbaObject(themePrimaryColor)

                // 計算強調色
                const themeHighlightColorObject = calcColor(rgbaObject, -32, -32, -32, 0)
                const themeHighlightColor = rgbaObject2Hex(themeHighlightColorObject)
                
                // 計算輔色
                const themeSecondaryColorObject = calcColor(rgbaObject, 94, 94, 94, 0)
                const themeSecondaryColor = rgbaObject2Hex(themeSecondaryColorObject)
                
                // 計算淺色
                const themeUndertoneColorObject = calcColor(rgbaObject, 150, 150, 150, 0)
                const themeUndertoneColor = rgbaObject2Hex(themeUndertoneColorObject)
                
                // 計算超淺色
                const themeSuColorObject = calcColor(rgbaObject, 220, 220, 220, 0)
                const themeSuColor = rgbaObject2Hex(themeSuColorObject)

                console.log('%c 強調色 ', `background:${themeHighlightColor};color:#ccc;`)
                console.log('%c 主色 ', `background:${themePrimaryColor};color:#ccc;`)
                console.log('%c 輔色 ', `background:${themeSecondaryColor};color:#fff;`)
                console.log('%c 淺色 ', `background:${themeUndertoneColor};color:#fff;`)
                console.log('%c 超淺 ', `background:${themeSuColor};color:#000;`)


                sessionStorage.themeHighlightColor = themeHighlightColor
                sessionStorage.themePrimaryColor = themePrimaryColor
                sessionStorage.themeSecondaryColor = themeSecondaryColor
                sessionStorage.themeUndertoneColor = themeUndertoneColor
                sessionStorage.themeSuColor = themeSuColor
                sessionStorage.themeBackgroundImage = themeBackgroundImage // '/ecda/resources/images/zhu1.png'


                document.documentElement.style.setProperty('--theme-highlight-color', themeHighlightColor);
                document.documentElement.style.setProperty('--theme-primary-color', themePrimaryColor);
                document.documentElement.style.setProperty('--theme-secondary-color', themeSecondaryColor);
                document.documentElement.style.setProperty('--theme-undertone-color', themeUndertoneColor);
                document.documentElement.style.setProperty('--theme-su-color', themeSuColor);
                document.documentElement.style.setProperty('--theme-background-image', '/ecda/resources/images/zhu1.png');

相關文章