CSS 如何更改多选下拉框中所选项目的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13515767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:51:04  来源:igfitidea点击:

how to change background color of selected items in multiselect dropdown box?

cssmulti-selecthtml.dropdownlistfor

提问by user9371102

I want to give the yellow color to the selected items in multiselect dropdown box. By default it has gray background after selecting, I want to do this in HTML, CSS.

我想在多选下拉框中为所选项目赋予黄色。默认情况下,选择后它具有灰色背景,我想在HTML, CSS.

Can any one help in this?

任何人都可以帮忙吗?

采纳答案by user9371102

We can use JS to select the DOMs.

我们可以使用 JS 来选择 DOM。

$('select').change(function() {
    $('option').css('background', 'none');
    $('option:selected').css('backgroundColor', 'red');
}).change()

<select>
    <option>1111111</option>
    <option>222222222</option>
    <option>33333333</option>
    <option>44444444</option>
</select>

Demo : http://jsfiddle.net/TxbVt/1/

演示:http: //jsfiddle.net/TxbVt/1/

回答by Vikash Gupta

We can simply do with the help of the below css.

我们可以简单地借助以下 css 来完成。

select option:checked{ background: #1aab8e -webkit-linear-gradient(bottom, #1aab8e 0%, #1aab8e 100%); }

select option:checked{ background: #1aab8e -webkit-linear-gradient(bottom, #1aab8e 0%, #1aab8e 100%); }

回答by Elnaz

<style>
     .select2-container--default .select2-results__option[aria-selected=true] {
        background-color: inherit;
        color: lightgray;
    }
</style>

Add your own style inside the block.

在块内添加您自己的样式。

回答by Pebbl

The following should work (for browsers that allow styling option tags), however the default select styling will override in most cases. You may be able to find a way to disable this however:

以下应该工作(对于允许样式选项标签的浏览器),但是在大多数情况下默认选择样式将被覆盖。但是,您可以找到禁用此功能的方法:

css

css

select option.selected {
  font-weight: bold;
  color: red;
}

javascript

javascript

function highlight_options(field){
  var i,c;
  for(i in field.options){
    (c=field.options[i]).className=c.selected?'selected':'';
  }
}

markup

标记

<select onchange="highlight_options(this)" multiple="multiple">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

回答by Anton Mitsev

Pure CSS would help here:

纯 CSS 在这里会有所帮助:

option:checked

回答by Diodeus - James MacFarlane

You can't.The <option>element does not accept CSS styling.

你不能。<option>元素不接受 CSS 样式。

You can used a JavaScript-based alternative. There are many <select>replacement scripts available.

您可以使用基于 JavaScript 的替代方案。有许多<select>替换脚本可用。