如何在Select元素中设置选定的项目背景颜色?

时间:2016-05-12 14:01:26

标签: c# asp.net colors html-select

我在Asp.net页面中添加了一个Select元素,在这个元素中的每个选项中我都设置了style="background-color: example_color"。正如本answer中所述。

当我调试网站并悬停选项时,会突出显示样式属性中指定的正确颜色,但在我选择它并选项卡到页面上的另一个元素后,背景颜色是正常的白色而不是蓝色或定义绿色。

问题: 如何在选择颜色后设置选项颜色?

  • 选择后选择元素:

enter image description here

代码:

选择元素标记:

     <div class="form-control">
       <label class="col-md-3 control-label" for="Current Status">Status</label>
       <div class="col-md-8">
          <select id="Status" name="Status" onchange="" class="form-control">
             <option style="background-color: blue" value="Down">Down</option>
             <option style="background-color: green" value="BCR">BCR</option>
          </select>
       </div>
 </div>

1 个答案:

答案 0 :(得分:1)

在任何类型的跨浏览器意义上,

<select>元素通常具有挑战性,因此请记住这一点,因为这可能无法在所有浏览器中使用。如果您需要,您可能需要使用select.css之类的第三方库或this thread, which explicitly avoid Javascript-based solutions中的一些建议。

您可以使用选项上提供的background-color属性在更改事件期间在父<select>元素上设置显式样式属性,如下所示:

<select id="Status" name="Status" onchange="colorizeMe(this);" class="form-control">
         <option style="background-color: blue!important" value="Down">Down</option>
         <option style="background-color: green!important" value="BCR">BCR</option>
</select>
<script>
    function colorizeMe(element){
      // Use the selected value to set the color
      element.options[element.selectedIndex].style.backgroundColor
      element.setAttribute('style','background-color: ' + element.options[element.selectedIndex].style.backgroundColor + '!important;');
    }
</script>

示例和代码段

enter image description here

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <select id="Status" name="Status" onchange="colorizeMe(this);" class="form-control">
    <option style="background-color: blue!important" value="Down">Down</option>
    <option style="background-color: green!important" value="BCR">BCR</option>
  </select>
  <script>
    function colorizeMe(element) {
      // Use the selected value to set hte color
      element.options[element.selectedIndex].style.backgroundColor
      element.setAttribute('style', 'background-color: ' + element.options[element.selectedIndex].style.backgroundColor + '!important;');
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;