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

如何通过JavaScript实现点击选项添加CSS样式,未选中时移除样式

解决方案

核心修改点

  • 修正closest拼写错误(原代码误写为closesst)
  • 点击选项时先清除所有选项的选中样式,再给当前选项添加样式
  • 调整CSS规则,让选中状态的边框和文字样式更精准

修改后的完整代码

HTML

<ul class="product_list">
  <li class="item">
    <h2>coke</h2>
    <p>$100</p>
  </li>
  <li class="item">
    <h2>beef</h2>
    <p>$600</p>
  </li>
</ul>

<h2 class="show">Your food of choice is <span class="plan"></span> The total price is <span class="price"></span></h2>

CSS

@charset "UTF-8";
.product_list {
  display: flex;
}

.product_list .item {
  border: 1px solid #ccc;
  border-radius: 6px;
  text-align: center;
  padding: 20px;
  margin: 20px;
  transition: border-color 0.2s;
}

.product_list .item h2 {
  margin-bottom: 16px;
}

.product_list .item:hover {
  border: 1px solid #222;
}

.show {
  border: 2px solid blue;
  padding: 20px;
}

/* 选中状态样式:item加粗边框,内部文字加粗 */
.bold {
  border: 3px solid #222 !important;
}
.bold h2, .bold p {
  font-weight: 900;
}

JavaScript

let plan = document.querySelector('.plan');
let price = document.querySelector('.price');
let items = document.querySelectorAll('.item');

for (var i = 0; i < items.length; i++) {
  items[i].addEventListener('click', showplan, false);
}

function showplan(e) {
  // 移除所有选项的选中样式
  items.forEach(item => item.classList.remove('bold'));
  
  // 获取当前点击的选项容器
  const currentItem = e.target.closest('li');
  
  // 给当前选项添加选中样式
  currentItem.classList.add('bold');
  
  // 更新选中的计划和价格
  const planSelected = currentItem.querySelector('h2');
  const priceSelected = currentItem.querySelector('p');
  plan.textContent = planSelected.textContent;
  price.textContent = priceSelected.textContent;
}

关键说明

  1. 全局样式重置:每次点击时遍历所有item移除bold类,确保同一时间只有选中项保留样式
  2. DOM方法修正:将错误的closesst改为正确的closest,才能精准定位到父级li元素
  3. 样式规则拆分:把边框样式绑定到li.item上,文字加粗样式绑定到内部的h2和p,逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:06:27