【问题标题】:Set Background color for a selected item in a Select option (multiple) [closed]为选择选项中的选定项目设置背景颜色(多个)[关闭]
【发布时间】:2011-08-04 03:56:58
【问题描述】:

我正在尝试更改列表框中所选项目的背景颜色(选择多个选项)。

我尝试过使用 css...我尝试过使用 JavaScript...和 ​​jquery...我真的不知道会发生什么!但我找不到答案:_(。

我在这个论坛上阅读了至少 10 个问题。我尝试了所有建议的解决方案,但我只能更改完整列表的背景……而不是所选项目。我发现的唯一方法是使用带有可点击列表项的无序列表,而不是如果我的选择 - 选项...但我正在使用表单,并且我想以传统方式将所选项目发送到服务器。

【问题讨论】:

  • 欢迎来到 SO。请编辑您的问题并添加一些代码,以便我们可以看到您尝试了什么?
  • 选择颜色是操作系统的偏好。
  • 我不认为这是可能的,虽然我可能错了。
  • 您可以在大多数浏览器中设置选项元素的样式属性,但在旧版 IE 中则不行。

标签: javascript jquery html css jquery-ui


【解决方案1】:

JavaScript

document.getElementById('your-select').onchange = function() {

    var options = this.getElementsByTagName('option'),
        selectedClassName = 'selected';

    for (var i = 0, length = options.length; i < length; i++) {
        var option = options[i],
            className = option.className;

        if (i == this.selectedIndex) {
            option.className += selectedClassName;
        } else {
            option.className = (' ' + className + ' ').replace(new RegExp('\\s' + selectedClassName + '\\s'), '');
        }
    }
};

jsFiddle.

CSS

#your-select option.selected {
    background: red;   
}

【讨论】:

  • IE8 怎么样?只有在 ff 和 chrome 上才能正常工作,您在 IE8 上的脚本不起作用。
  • @mcmwhfy IE8 有什么问题?错误?
  • 在 IE8 上,选择保留在选择框中,而不是在列表中(
  • @mcmwhfy 你能举个例子说明它在jsfiddle.net 上不起作用吗?
  • 检查此打印屏幕:postimage.org/image/lrj00um9n
【解决方案2】:

看起来它不想打球:

<style>

::selection {
   background: #FF0000; /* Safari */
   }
::-moz-selection {
   background: #FF0000; /* Firefox */
}
</style>

<select multiple="true">
<option><span style="background:FF0000;">One</span></option>
<option>Two</option>
<option>Three</option>
</select>

<p>This is text.</p>

这并不让我感到惊讶。以我的经验,小部件通常对这种样式有抵抗力。像 Hussein 的方法一样,自己动手,看起来是你唯一的出路。

【讨论】:

    【解决方案3】:

    这将改变所选选项的背景颜色

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

    http://jsfiddle.net/TxbVt/1/查看工作示例

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 2011-10-26
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多