简体   繁体   English

在 Svelte 组件中切换类

[英]Toggle Classes in Svelte Component

Consider this Svelte code:考虑这个 Svelte 代码:

https://svelte.dev/repl/e3ea17e8e09044999bf7cb4bc882adea?version=3.19.2 https://svelte.dev/repl/e3ea17e8e09044999bf7cb4bc882adea?version=3.19.2

How can I adjust this so that each button can be toggled independently?我该如何调整才能使每个按钮都可以独立切换? As you can see it currently toggles all of the buttons:(如您所见,它当前会切换所有按钮:(

You have to maintain the state for each button like so:您必须像这样维护每个按钮的状态:

<script>let active = {button1: false, button2: false, button3: false};</script>

<style>.active {background-color: #ff3e00; color: white;}</style>

<button class:active="{active.button1}" on:click="{() => active.button1 = !active.button1}">foo</button>
<button class:active="{active.button2}" on:click="{() => active.button2 = !active.button2}">bar</button>
<button class:active="{active.button3}" on:click="{() => active.button3 = !active.button3}">baz</button>

So for those wanting a more in-depth answer to the above, I've created a svelte button component that allows toggling and opening of links at this REPL所以对于那些想要更深入地回答上述问题的人,我创建了一个细长的按钮组件,允许在这个 REPL 上切换和打开链接

https://svelte.dev/repl/c5b48ef759d045d08d17b5f11b74e82e?version=3.19.2 https://svelte.dev/repl/c5b48ef759d045d08d17b5f11b74e82e?version=3.19.2

Enjoy!享受!

An alternative to either having to make a new component or creating a variable for tracking is to use the class that you want to toggle.除了必须创建新组件或创建用于跟踪的变量之外,另一种方法是使用要切换的 class。 As an example:举个例子:

element.classList.toggle('className');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM