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

多主题法案高亮交互Bug修复:多按钮选择功能失效问题

解决主题高亮法案的筛选逻辑问题

我们需要实现基于主题按钮筛选法案的功能:点击Education、Contraception、LGBTQ按钮时,非相关法案通过.fade类降低透明度。其中HB 104同时关联Education和Contraception,仅当三个按钮全选或仅点击LGBTQ按钮时才需要变灰。当前代码仅在单按钮选择时正常,多按钮选择时逻辑失效,以下是修复后的完整方案:

修正后的完整代码

HTML

<div class="buttons">
  <button id="edu_button" style="background:black; color:white;" issue="education">Education</button>
  <button id="ca_button" style="background:black; color:white;" issue="contraception">Contraception</button>
  <button id="lgbtq_button" style="background:black; color:white;" issue="lgbtq">LGBTQ</button>
</div>
<br/>
<div class="bill" issue="education">HB 101 (Education bill)</div>
<div class="bill" issue="contraception">HB 102 (Contraception bill)</div>
<div class="bill" issue="lgbtq">HB 103 (LGBTQ bill)</div>
<div class="bill" issue="education contraception">HB 104 (Bill that involves education and contraception)</div>

CSS

.fade{
   opacity: 0.2;
}

JavaScript

// 追踪已激活的主题集合
const activeThemes = new Set();
const buttons = document.querySelectorAll('.buttons button');
const bills = document.querySelectorAll('.bill');

// 绑定按钮点击事件:切换选中状态并更新法案显示
buttons.forEach(button => {
  button.addEventListener('click', () => {
    const theme = button.getAttribute('issue');
    // 切换按钮样式与激活状态
    if (activeThemes.has(theme)) {
      activeThemes.delete(theme);
      button.style.background = 'black';
    } else {
      activeThemes.add(theme);
      button.style.background = '#ec0d7d';
    }
    // 更新所有法案的显示状态
    updateBillVisibility();
  });
});

// 核心筛选逻辑
function updateBillVisibility() {
  const activeArray = Array.from(activeThemes);
  const isAllSelected = activeArray.length === 3;
  const isOnlyLGBTQ = activeArray.length === 1 && activeArray[0] === 'lgbtq';

  bills.forEach(bill => {
    const billThemes = bill.getAttribute('issue').split(' ');
    // 判断当前法案是否与激活主题有交集
    const hasMatchingTheme = billThemes.some(theme => activeThemes.has(theme));

    // 处理HB104的特殊规则
    if (billThemes.includes('education') && billThemes.includes('contraception')) {
      if (isAllSelected || isOnlyLGBTQ) {
        bill.classList.add('fade');
      } else {
        bill.classList.remove('fade');
      }
    } else {
      // 普通法案规则:匹配激活主题则显示,否则变灰
      bill.classList.toggle('fade', !hasMatchingTheme);
    }
  });
}

修复说明

  1. 统一状态管理:用Set集合追踪激活的主题,替代原有的独立颜色切换与事件绑定逻辑,避免多按钮点击时的状态冲突
  2. 完善筛选逻辑:
    • 对每个法案判断其关联主题是否与激活主题有交集
    • 单独处理HB104的特殊规则:仅当全选按钮或仅选中LGBTQ时添加灰化效果
  3. 移除内联事件:删除HTML中的onclick内联属性,改用事件监听绑定,使逻辑更集中易维护

修复后可满足所有场景需求:

  • 单按钮选择:对应主题法案正常显示,其余灰化(HB104在选Education/Contraception时正常显示)
  • 多按钮组合(如Education+Contraception):HB101、HB102、HB104正常显示,HB103灰化
  • 全选按钮:所有法案灰化
  • 仅选LGBTQ:仅HB103正常显示,其余(包括HB104)灰化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:25:26