返回到原始CSS变量值的JavaScript切换按钮问题



我正在尝试制作一个切换开关,以更改我设置的颜色变量。以下代码有效,但如果再次单击,我希望它恢复到原始颜色。此外,如果有更好的方法来实现这一点,我想学习如何做到,这似乎是最直接的方法,但我仍在学习香草JS。

CSS:

:root {
--bg-color:  #040d14;
--text-color:  #f0f4f6;
--border-color: #30363a;
--highlight-color: #00c805; 
--secondary-bg-color:#1e2124;
}

JS:

change.onclick = () => {
document.documentElement.style.setProperty('--bg-color', '#f7f7f7');
document.documentElement.style.setProperty('--text-color', '#333');
document.documentElement.style.setProperty('--border-color', '#040d14');
document.documentElement.style.setProperty('--secondary-bg-color', '#ebecec');

}

所以对我来说,这看起来像是在黑暗/光明模式之间切换。有很多关于这方面的教程,但这是它的基础

const button = document.querySelector('button')
button.addEventListener('click', toggleTheme)
function toggleTheme() {
if (document.body.getAttribute('data-theme') === 'light') {
document.body.setAttribute('data-theme', 'dark')
} else {
document.body.setAttribute('data-theme', 'light')
}
}
:root {
--bg-color:  #040d14;
--text-color:  #f0f4f6;
--border-color: #30363a;
--highlight-color: #00c805; 
--secondary-bg-color:#1e2124;
}
[data-theme="light"] {
--bg-color:  #f7f7f7;
--text-color:  #333;
--border-color: #040d14;
--highlight-color: #ebecec; 
--secondary-bg-color:#1e2124;
}


.container {
background-color: var(--bg-color);
height: 200px;
color: var(--text-color);
border: 1px solid var(--border-color);
}
<div class="container">
Stuff
</div>
<button>Toggle</button>

我认为你的方式是最好的方式。要删除,可以使用.removeProperty()

document.documentElement.style.removeProperty("--bg-color")

编辑

如何在两种状态之间切换的示例。您还可以使用JavaScript设置初始CSS自定义属性,如果您有多个未预定义的选项,这将非常有用。

<div class="container"></div>
:root {
--bg: red;
}
.container {
width: 200px;
height: 200px;
background: var(--bg);
}
let theme = "red"
const container = document.querySelector(".container")
container.addEventListener("click", function() {
if (theme === "red") {
theme = "blue"
document.documentElement.style.setProperty("--bg", "blue")
return
}
theme = "red"
document.documentElement.style.removeProperty("--bg")
})

最新更新