苗条的#each风格
Svelte #each Style
我正在使用类似于以下代码的每个块。我有一个迭代的项目数组,然后为所有项目创建一个按钮。
<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>
但我想对按钮进行独特的设计。例如,我希望第一个按钮是红色和方形的,下一个是黄色和圆形的,最后一个是正常的。我将如何将其添加到上面的示例中?
我可以看到几种方法:
使用 nth-child()
选择器为每个按钮设置不同的样式:
li:nth-child(1) > button { color: red; }
li:nth-child(2) > button { color: green; }
根据索引
从数组中添加一个不同的class
<script>
const classes = ['green', 'red', 'yellow']
</script>
{#each item as item, i}
<li class={classes[i]}>...</li>
{/each}
(如果你想让 classes 重复,你可以在这里使用模运算符)
最后一种方法是从函数中检索 classes(这与第一种非常相似,但更灵活)
<script>
function getClasses(index) {
return 'something here';
}
</script>
{#each item as item, i}
<li class={getClasses(i)}>...</li>
{/each}
如果您不想使用 classes,您当然可以使用样式来做类似的事情
<script>
function getStyle(index) {
return 'something here';
}
</script>
{#each item as item, i}
<li style={getStyle(i)}>...</li>
{/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>
但我想对按钮进行独特的设计。例如,我希望第一个按钮是红色和方形的,下一个是黄色和圆形的,最后一个是正常的。我将如何将其添加到上面的示例中?
我可以看到几种方法:
使用 nth-child()
选择器为每个按钮设置不同的样式:
li:nth-child(1) > button { color: red; }
li:nth-child(2) > button { color: green; }
根据索引
从数组中添加一个不同的class<script>
const classes = ['green', 'red', 'yellow']
</script>
{#each item as item, i}
<li class={classes[i]}>...</li>
{/each}
(如果你想让 classes 重复,你可以在这里使用模运算符)
最后一种方法是从函数中检索 classes(这与第一种非常相似,但更灵活)
<script>
function getClasses(index) {
return 'something here';
}
</script>
{#each item as item, i}
<li class={getClasses(i)}>...</li>
{/each}
如果您不想使用 classes,您当然可以使用样式来做类似的事情
<script>
function getStyle(index) {
return 'something here';
}
</script>
{#each item as item, i}
<li style={getStyle(i)}>...</li>
{/each}