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

如何为select标签中的选中选项单独设置背景颜色

解决下拉列表选中选项背景色设置问题

浏览器对<select>和<option>的默认样式限制较多,直接给option加background-color在选中状态下容易被浏览器默认样式覆盖,你可以试试以下两种方法:

方法一:CSS 伪类控制

通过:checked伪类选中当前激活的option,配合!important强制覆盖默认样式,同时同步设置select控件本身的背景色,保持视觉统一:

/* 设置选中option的背景色和文字颜色 */
option:checked {
  background-color: #333333 !important;
  color: white;
}

/* 同步select控件的背景色 */
select.form-control.form-control-sm {
  background-color: #333333;
  color: white;
}

方法二:JavaScript 辅助控制

如果CSS方案在部分浏览器(如Chrome)仍不生效,可以用JS监听选择事件,动态控制样式,兼容性更好:

<select name="Occupancy Status" class="form-control form-control-sm" id="occupancySelect">
  <option selected>Select your Occupany Status</option>
  <option>bla bla</option>
  <option>bla bla</option>
  <option>bla bla</option>
</select>

<script>
const selectEl = document.getElementById('occupancySelect');
// 初始化样式
selectEl.style.backgroundColor = '#333333';
selectEl.style.color = 'white';
selectEl.options[selectEl.selectedIndex].style.backgroundColor = '#333333';
selectEl.options[selectEl.selectedIndex].style.color = 'white';

// 监听选择变化
selectEl.addEventListener('change', function() {
  // 重置所有option样式
  Array.from(this.options).forEach(opt => {
    opt.style.backgroundColor = '';
    opt.style.color = '';
  });
  // 设置当前选中项样式
  const selectedOpt = this.options[this.selectedIndex];
  selectedOpt.style.backgroundColor = '#333333';
  selectedOpt.style.color = 'white';
  // 更新select控件样式
  this.style.backgroundColor = '#333333';
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:27:26