【问题标题】:Using Svelte, how do I populate a <style> tag in <svelte:head> with a Javascript string variable?使用 Svelte,如何使用 Javascript 字符串变量填充 <svelte:head> 中的 <style> 标记?
【发布时间】:2026-01-16 22:30:01
【问题描述】:

使用 Svelte,我想要完成的是能够使用我拥有的 post 对象的 css 属性设置我的 html 样式。

我想,没问题,只需将样式标签添加到我的svelte:head{post.css}。它将我的post.css 数据直接放入样式标签,中提琴,问题解决了。但是,不,问题没有解决。当我在浏览器中查看元素时,我看到了

&lt;style&gt;{post.css}&lt;/style&gt;

而不是

<style>
  p{
    color: purple;
    font-weight: 900;
  }
 </style>

我创建了一个解决方法,我在&lt;style&gt; 标记之后设置了innerText onMount,但我不喜欢它,并且希望以更简洁的方式来做。

我想要什么……

<script>
  export let post = {
    html: `<p>This is purple</p>`,
    css : `
      p{
        color: purple;
        font-weight: 900;
      }
    `
    }  
</script>

<svelte:head>
  <style>{post.css}</style>
</svelte:head>

{@html post.html}

我必须做些什么才能让它发挥作用……

<script>
  import { onMount } from "svelte";

  export let post = {
    html: `<p>This is purple</p>`,
    css : `
      p{
        color: purple;
        font-weight: 900;
      }
    `
    }

  onMount(() => {
    let styler = document.getElementById("styler");
    styler.innerText = post.css
  });
</script>

<svelte:head>
  <style id="styler"></style>
</svelte:head>

{@html post.html}

如果您有任何其他替代方法可以使用css 属性来设置post 对象的html 属性的样式,或者知道如何让Svelte 识别{post.css}&lt;style&gt; 标记中,请让我知道。

【问题讨论】:

    标签: svelte sapper css-in-js


    【解决方案1】:

    你可以这样做:

    {@html `<style>${post.css}</style>`}
    

    请记住,post.css 中的样式将应用于整个页面,而不仅仅是帖子的 HTML。

    Demo

    【讨论】: