如何在Svelte中设置事件的全局风格

时间:2019-07-28 09:23:00

标签: svelte

我已经用Svelte编写了一个应用程序,想添加一个黑暗模式,任何人都可以在单击按钮后激活它。我添加了一个名为isDarkMode的属性来切换这两种情况。如果该属性为true,我想将主体的背景颜色更改为深色,但背景颜色不变。

{#if isDarkMode}
    <style>
        :global(body){
            background: #2e3440;
        }
    </style>
{/if}

2 个答案:

答案 0 :(得分:5)

Svelte中的style标记不像Svelte文件的其他部分那样反应灵敏(需要引用)。因此,一旦文件编译完毕,就会生成CSS(唯一的ID,动画和其他好东西)。

我将采用另一种方法来实现“黑暗模式”。非“ JS-in-JS”领域的一种常见方法是将主题类添加到def __getattr__(self, action): def method(*args,**kwargs): print(action,args,kwargs) print(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])") return eval(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])") return method 标记中。

  1. 为所有页面和组件定义默认样式(如果可以,请定义为“浅色模式”。
  2. 通常以CSS方式定义body标签启用主题时的覆盖。

您需要使用切换开关或其他方式来触发“黑暗模式”(例如一天中的时间)。在此示例中,它是一个Button组件:

body

这就是全部。然后,对于您的<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)放在其中,则会丢失Svelte为组件生成的唯一ID,这会影响所有按钮。

Demo in REPL

答案 1 :(得分:3)

如果您愿意使用css变量来管理主题,则可以使用<svelte:head>标签在Svelte中切换样式表:

<script>
    let dark = false;
    const toggleTheme = () => dark = dark === false
</script>

<svelte:head>
    {#if dark}
    <link rel="stylesheet" href="change/this/path/dark-theme.css">
    {/if}
</svelte:head>

<h1>Hello World!</h1>

<button on:click={toggleTheme}>
    toggle theme
</button>

这应该使您更轻松地管理整个应用程序中的样式,并减小包的总大小,并避免在CSS中使用:global选择器。

您可以在此处找到有效的演示: https://svelte.dev/repl/1a121a39eddb4b3682a7701a35ac6824?version=3.6.9