admin管理员组文章数量:1356701
Consider this Svelte code:
/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 :(
Consider this Svelte code:
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 :(
Share Improve this question edited Jun 8, 2023 at 7:26 Anurag Srivastava 14.5k4 gold badges37 silver badges46 bronze badges asked Mar 8, 2020 at 21:23 Timmy LeeTimmy Lee 8051 gold badge12 silver badges25 bronze badges 2- Seems like you have modified the code in the REPL since asking? Would be nice for visitors from the future to post the relevant code in the question. SO likes having its threads self contained and not dependent on the content of external links that can change ;) – rixo Commented Mar 8, 2020 at 21:47
- yeah.. no probs.. i'll revert it and start a new repl for what i'm working on :D – Timmy Lee Commented Mar 9, 2020 at 9:55
3 Answers
Reset to default 7You 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 ponent that allows toggling and opening of links at this REPL
https://svelte.dev/repl/c5b48ef759d045d08d17b5f11b74e82e?version=3.19.2
Enjoy!
An alternative to either having to make a new ponent or creating a variable for tracking is to use the class that you want to toggle. As an example:
element.classList.toggle('className');
本文标签: javascriptToggle Classes in Svelte ComponentStack Overflow
版权声明:本文标题:javascript - Toggle Classes in Svelte Component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744027313a2578271.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论