代码之家  ›  专栏  ›  技术社区  ›  SoZettaSho

在Svelte中以编程方式添加(作用域)类名

  •  0
  • SoZettaSho  · 技术社区  · 2 年前

    代码段:

    <script>
      let coloredText = "This is colored text"
        let templateString = `This text is programmatically inserted`;
      let templateHtml = `<span class="colored">I want this text to be red</span></h1>`
      
    </script>
    
    <style>
      .colored {
        color: red;
      }
    
      main {
        font-family: sans-serif;
        text-align: center;
      }
    </style>
    
    <main>
        <h1>This is normal text</h1>
      <h1><span class="colored">{coloredText}</span></h1>
        <h1>{templateString}</h1>
      <h1>{@html templateHtml}</h1>
        
    </main>
    

    输出

    enter image description here

    Codesandbox

    当您向元素添加css类时,Svelte似乎添加了一个额外的 svelte-xxxx 类转换为(样式正确的)结果标记。它不会将相同的类添加到用 @html 标记,并且生成的标记没有样式化,即使CSS选择器应该与生成的元素匹配。

    在Svelte中,向程序生成的HTML添加类名的规范方法是什么?我知道 :global 但我希望将结果的范围保持为组件。

    0 回复  |  直到 2 年前
        1
  •  2
  •   Corrl    2 年前

    使用 :global(...) modifier 与组件内部的包装元素相结合将保持样式的作用域

     h1 :global(.colored) {
        color: red;
      }
    

    ->

    h1.svelte-nd95r3 .colored {
        color: red;
    }