如何从Svelte中已经存在的具有相同Css的标签中删除Css类

  • 本文关键字:Css 标签 删除 存在 Svelte svelte
  • 更新时间 :
  • 英文 :


首先,如果这个问题没有多大意义,我很抱歉。发现很难正确地提出问题,但这正是我想要做的。

当前行为能够在两个h1标签之间切换css类,但启用切换后无法切换;意味着无法在已经启用css类的h1标签上删除css类。

预期行为单击同一活动h1时,它应该删除css类。

链接到REPL,也是下面相同的代码。

应用

<script>
import Component2 from './Component2.svelte'
let numbers = [1,2];
let selectedOption;
const runThis = (i) => {
selectedOption = i;
}
</script>
{#each numbers as number}
<Component2 isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}

组件速度

<script>
export let number;
export let isSelected;
</script>
<h1 on:click class:red={isSelected}>Hello {number}</h1>
<style>
.red{
color: red;
}
</style>

切换的问题是,您必须确保新选择的数字不是已经选择的数字。因此,如果当前selectedOptioni相同,只需将其设置为null:

const runThis = (i) => {
selectedOption = i !== selectedOption ? i : null;
}

请参阅REPL。

找到答案

应用程序苗条

<script>
import Component from './Component.svelte'
let numbers = [1,2];
let selectedOption;
const runThis = (i) => {
if(selectedOption===i)
selectedOption=-1
else
selectedOption = i;
}
</script>
{#each numbers as number}
<Component isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}

组件苗条

//same

最新更新