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

如何实现符合特定规则的复选框列表展开/折叠逻辑?求最优方案

复选框列表展示逻辑与实现

逻辑规则

  • 展开状态始终显示所有可用项。
  • 默认折叠状态下最多显示2项。
  • 选中项需始终位于列表顶部。
  • 若选中项超过2个,折叠状态下需显示所有选中项。
  • 无选中项时,折叠状态下最多显示2项。
  • 仅选中1项时,折叠状态下显示该选中项加1个未选中项,以维持最少2项的显示数量。

当前实现代码

<script>
  let checkboxes = [
    { id: 1, label: 'Checkbox 1', checked: false },
    { id: 2, label: 'Checkbox 2', checked: false },
    { id: 3, label: 'Checkbox 3', checked: false },
    { id: 4, label: 'Checkbox 4', checked: false },
    { id: 5, label: 'Checkbox 5', checked: false },
    { id: 6, label: 'Checkbox 6', checked: false },

    // Add more checkboxes as needed
  ];

  let isExpanded = false;

  function toggleExpand() {
    isExpanded = !isExpanded;
  }
</script>


<div class="checkbox-list">
  {#each (isExpanded ? checkboxes : checkboxes.slice(0, 2)) as checkbox (checkbox.id)}
    <label>
      <input type="checkbox" bind:checked={checkbox.checked} />
      {checkbox.label}
    </label>
  {/each}
  {#if checkboxes.length > 2}
    <button on:click={toggleExpand}>
      {#if isExpanded}Collapse{:else}Expand{/if}
    </button>
  {/if}
</div>

<style>
    div { display: flex; flex-direction: column; }

    label:has(input:checked) {
        order: -9999;
    }
</style>

我不确定当前实现是否为最优方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:13:21