跳到主要內容

在建構使用者介面時,您通常會發現自己處理資料列表。在這個練習中,我們多次重複了 <button> 標記,每次都更改顏色,但仍有更多需要新增。

我們可以擺脫除了第一個按鈕之外的所有按鈕,然後使用 each 區塊,而不是費力地複製、貼上和編輯。

App
<div>
	{#each colors as color}
		<button
			style="background: red"
			aria-label="red"
			aria-current={selected === 'red'}
			onclick={() => selected = 'red'}
		></button>
	{/each}
</div>

運算式(在此例中為 colors)可以是任何可迭代或類似陣列的物件,換句話說,任何可以與 Array.from 一起運作的物件。

現在我們需要在 "red" 的位置使用 color 變數。

App
<div>
	{#each colors as color}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		></button>
	{/each}
</div>

您可以將目前索引作為第二個參數取得,如下所示:

App
<div>
	{#each colors as color, i}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		>{i + 1}</button>
	{/each}
</div>

在 GitHub 上編輯此頁面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<script>
	const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
	let selected = $state(colors[0]);
</script>
 
<h1 style="color: {selected}">Pick a colour</h1>
 
<div>
	<button
		style="background: red"
		aria-label="red"
		aria-current={selected === 'red'}
		onclick={() => selected = 'red'}
	></button>
 
	<button
		style="background: orange"
		aria-label="orange"
		aria-current={selected === 'orange'}
		onclick={() => selected = 'orange'}
	></button>
 
	<button
		style="background: yellow"
		aria-label="yellow"
		aria-current={selected === 'yellow'}
		onclick={() => selected = 'yellow'}
	></button>
 
	<!-- TODO add the rest of the colours -->
	<button></button>
	<button></button>
	<button></button>
	<button></button>
</div>
 
<style>
	h1 {
		transition: color 0.2s;
	}
 
	div {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		grid-gap: 5px;
		max-width: 400px;
	}
 
	button {
		aspect-ratio: 1;
		border-radius: 50%;
		background: var(--color, #fff);
		transform: translate(-2px,-2px);
		filter: drop-shadow(2px 2px 3px rgba(0,0,0,0.2));
		transition: all 0.1s;
	}
 
	button[aria-current="true"] {
		transform: none;
		filter: none;
		box-shadow: inset 3px 3px 4px rgba(0,0,0,0.2);
	}
</style>