You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中each循环渲染输入框时如何仅修改事件目标背景色

问题根源

所有可编辑输入框的class都绑定了同一个全局响应式变量color,只要输入事件触发修改了该变量值,所有引用它的输入框都会同步更新样式,必然出现全量变色的问题。

修复方案
  • 移除全局单个color变量,新增与scrambledMessage长度一致的颜色状态数组,每个索引位对应同位置输入框的背景样式,初始值全部设为白色。
  • 调整handleInput逻辑:输入触发时仅修改当前输入框对应索引位的颜色值,不修改全局状态;取值使用event.target.value避免删除内容时值获取异常,同时将事件拿到的字符串类型id转为数字,匹配数组索引。
  • 循环渲染可编辑输入框时,class绑定当前索引位对应的颜色数组值,不再绑定全局变量;修改数组索引值后手动触发响应式更新,保证视图同步。
修正后完整代码
<script>
    let scrambledMessage = ["h","","","",""," ","t","o","d","","y"]
    let answer = ["h","e","l","l","o"," ","t","o","d","a","y"];
    
    const colorCode = { white: 'bg-white', red: 'bg-red-500', green: 'bg-green-500' };
    // 按输入位置初始化对应颜色状态,默认全部白色
    let inputColors = new Array(scrambledMessage.length).fill(colorCode.white);
    
    const handleInput = (event) => {
        const val = event.target.value;
        const index = Number(event.target.id);
        
        if (val === answer[index]) {
            inputColors[index] = colorCode.green;
        } else if (val === '') {
            inputColors[index] = colorCode.white;
        } else {
            inputColors[index] = colorCode.red;
        }
        // 触发数组响应式更新,同步视图
        inputColors = [...inputColors];
    };
</script>
<svelte:head>
    <link src="https://cdn.tailwindcss.com">
</svelte:head>
<div class="bg-black p-20 text-black">
    {#each scrambledMessage as mes, i}
        {#if mes === ' '}
            <input
                class="bg-gray-500 w-12 px-4 py-2 border mx-2 rounded text-center border-purple-500"
                disabled />
        {:else if mes === ''}
            <input
                class="{inputColors[i]} w-12 px-4 py-2 border mx-2 rounded text-center border-purple-500"
                placeholder={mes}
                id={i}
                on:input={handleInput}
                maxlength="1"
                value={mes} />
        {:else}
            <input
                class="bg-white w-12 px-4 py-2 border mx-2 rounded text-center border-purple-500"
                value={mes}
                disabled />
        {/if}
    {/each}
</div>

内容的提问来源于stack exchange,提问作者Tracy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:51:05