【发布时间】:2021-01-31 15:30:45
【问题描述】:
我想用 SASS 预处理器在 CSS 中构建一个简单的主题颜色切换器。例如,当我单击按钮时,背景颜色会从白色变为黑色/黑色变为白色。该功能适用于我的 div 按钮,但不适用于我的身体(设置了背景颜色)。你知道为什么吗?
谢谢
HTML
<body>
<div class="container">
<button class="toggle-btn">Toggle theme</button>
</div>
</body>
CSS/SCSS
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: inherit;
}
:root {
font-size: 14px;
}
body {
box-sizing: border-box;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
.dark-theme & {
background-color: black;
}
}
.container {
border: 2px solid red;
height: 500px;
width: 1000px;
display: flex;
justify-content: center;
align-items: center;
transition: all .3s;
.dark-theme & {
background-color: black;
}
}
.toggle-btn {
background-color: black;
color: white;
padding: 15px;
.dark-theme & {
background-color: white;
color: black;
}
}
JS
const toggleBtn = document.querySelector('.toggle-btn');
toggleBtn.addEventListener('click', () => document.body.classList.toggle('dark-theme'));
【问题讨论】: