我已经用 Svelte 编写了一个应用程序,并想添加一个任何人都可以在单击按钮后激活的暗模式。我添加了一个名为 isDarkMode 的属性来切换两种情况。如果属性为true,我想把body的背景色改成深色,但是背景色没有变化。
{#if isDarkMode}
<style>
:global(body){
background: #2e3440;
}
</style>
{/if}
最佳答案
Svelte 中的样式标签不像 Svelte 文件的其他部分那样具有反应性(需要引用)。因此,一旦文件被编译,就会生成 CSS(唯一 ID、动画和其他好东西)。
我会采取不同的方法来实现“暗模式”。非“CSS-in-JS”领域的常见方法是向 body
添加主题类。标签。
你需要一个开关或其他东西来触发“黑暗模式”(例如一天中的时间)。在这个例子中,它是一个 Button 组件:
<script>
function toggle() {
window.document.body.classList.toggle('dark-mode')
}
</script>
<button on:click={toggle}>Toggle mode</button>
仅此而已。那么对于您的
body
对于其他组件,您可以相应地设置样式:// App.svelte
<style>
:global(body) {
background-color: #f2eee2;
color: #0084f6;
transition: background-color 0.3s
}
:global(body.dark-mode) {
background-color: #1d3040;
color: #bfc2c7;
}
</style>
// Button.svelte or any other component that adjusts to mode
<style>
button {
background-color: #f76027;
color: white;
border: none;
border-radius: 4px;
padding: 0.5rem;
text-transform: uppercase;
}
:global(body.dark-mode) button {
background-color: #0084f6;
color: white;
}
</style>
请注意,只有正文部分(无双关语)是全局的
:global(body.dark-mode)
.如果你把 button
在内部,您将丢失 Svelte 为您的组件生成的唯一 ID,它会影响所有按钮。Demo in REPL
关于svelte - 如何在 Svelte 中设置事件的全局样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57239504/