0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

svelte classを動的につける

Last updated at Posted at 2023-01-17

結論

<div class:クラス名={条件}></div>

クリックされた文字にselectedクラスをつけて文字を赤くする。

image.png

<script>
	let current = 'apple';
</script>

<div>
	<ul>
		<li class:selected={current === 'apple'} on:click={() => (current = 'apple')}>
			りんご
		</li>
		<li class:selected={current === 'banana'} on:click={() => (current = 'banana')}>
			バナナ
		</li>
		<li class:selected={current === 'grape'} on:click={() => (current = 'grape')}>
			ぶどう
		</li>
	</ul>
</div>

<style>
	.selected {
		color: red;
	}
</style>

その他

上記の例では、あるクラスをつけるかつけないかしか制御できない。
条件により違うクラスをつける場合は、

<div>
	<ul>
		<li class:selected={current === 'apple'} on:click={() => (current = 'apple')}>
			りんご
		</li>
		<li class:selected={current === 'banana'} on:click={() => (current = 'banana')}>
			バナナ
		</li>
		<li class:selected={current === 'grape'} on:click={() => (current = 'grape')}>
			ぶどう
		</li>
	</ul>
</div>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?