【问题标题】:Svelte #each Style苗条#每种风格
【发布时间】:2021-09-02 14:44:58
【问题描述】:

我正在使用类似于以下代码的 each 块。我有一个迭代的项目数组,然后为所有项目创建一个按钮。

<ul>
    {#each cats as { id, name }, i}
        <li><button target="_blank" href="https://www.youtube.com/watch?v={id}">
            {i + 1}: {name}
        </button></li>
    {/each}
</ul>

但我想对按钮进行独特的风格化。例如,我希望第一个按钮是红色和方形的,下一个是黄色和圆形的,最后一个是正常的。我将如何将它添加到上面的示例中?

【问题讨论】:

    标签: svelte svelte-3


    【解决方案1】:

    我认为有几种方法可以做到这一点:

    使用nth-child() 选择器为每个按钮设置不同的样式:

    li:nth-child(1) > button { color: red; }
    li:nth-child(2) > button { color: green; }
    

    根据索引从数组中添加不同的类

    <script>
      const classes = ['green', 'red', 'yellow']
    </script>
    {#each item as item, i}
      <li class={classes[i]}>...</li>
    {/each}
    

    (如果你想让类重复,你可以在这里使用模运算符)

    最后一种方法是从函数中检索类(这与第一种非常相似,但更灵活)

    <script>
      function getClasses(index) {
        return 'something here';
      }
    </script>
    {#each item as item, i}
      <li class={getClasses(i)}>...</li>
    {/each}
    

    如果你不想使用类,你当然可以用样式做类似的事情

    <script>
      function getStyle(index) {
        return 'something here';
      }
    </script>
    {#each item as item, i}
      <li style={getStyle(i)}>...</li>
    {/each}
    

    【讨论】:

    • 使用第一种方法,我可以使用javascript将值传递给第n个孩子吗...所以代替:li:nth-​​child(1)=>我可以调用x = 5然后在脚本中将其传递给第 n 个孩子,例如 li:nth-child(x)
    • 不,你不能,你可以在 svelte 中的 javascript 和 css 之间进行通信的唯一方法是将其添加到样式属性:style="color: red;" 你可以在这里使用 css 变量:style="--myvar: 122px"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多