admin管理员组

文章数量:1392095

Consider this Svelte code

{#each filters as filters, i}
   <div class='filter-container'>
      <div class='button filter' on:click={ () => setFilter(filters.name, filterContext)}>{filters.name}</div>          
   </div>
{/each}

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

Consider this Svelte code

{#each filters as filters, i}
   <div class='filter-container'>
      <div class='button filter' on:click={ () => setFilter(filters.name, filterContext)}>{filters.name}</div>          
   </div>
{/each}

The above filter buttons are made depending on how many filters there are in some js object. How can I create a class that is toggled for all filter buttons when the one button is clicked.

eg. when one is active all the others are not?

Share Improve this question edited May 30, 2020 at 21:49 doğukan 27.7k13 gold badges63 silver badges75 bronze badges asked May 30, 2020 at 21:48 Timmy LeeTimmy Lee 8051 gold badge12 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Class are just strings - in svelte you can bind them to an expression as any other attribute.

For example:

<div class={'button filter ' + (activefilter === filters.name ? 'isactive' : '')}/>

when activefilter === filters.name is true, then the button class will became 'button filter isactive'

A special short syntax to toggle classes is provided too. Find more here

We can easily bind class names to expressions, so that the class will be added if the expression bees truthy:

<script>
    let isActive = false
</script>

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

<h1 class:active={isActive}>Hello!</h1>
<button on:click={() => isActive = !isActive}>Click me</button>

Here, clicking the button toggles the isActive boolean. The class active is bound to that variable on the h1 element and you can see that the color now changes on every button click.

That is the standard way on how to set single classes dynamically.

REPL: https://svelte.dev/repl/988df145876a42c49bb8de51d2cae0f2?version=3.23.0

本文标签: javascriptToggle class on buttons in SvelteStack Overflow