更改选择元素中选项的颜色

时间:2015-08-21 11:31:37

标签: javascript jquery html

我正在尝试更改选定元素中所选选项的颜色,当它在下拉菜单中时显示在主窗口中。到目前为止,我已经能够改变所有选项的颜色。

        <select id="drop-down" onchange="colorChange(event);">
           <option value="">--</option>
           <option value="one">one</option>
           <option value="two">two</option>
           <option value="three">three</option>
           <option value="four">four</option>
        </select>

这是我正在使用的功能。

       var one = "one";
       var two = "two";
       var three = "three";
       var four = "four";

       function colorChange(event){
          if(event.target.value == one){
            event.target.style.color = "#67D986";
          } else if (event.target.value == two || three || four){
            event.target.style.color = "#f00";  
          } else{ 
             alert("There has been an error!!!");
       }

    };

3 个答案:

答案 0 :(得分:1)

String originalStr = "emoji-" + newString(0x1f602) +newString(0x1f684)+"--over"; public static final String newString(int codePoint) { return new String(Character.toChars(codePoint)); } else if条件中存在问题,要在OR中添加条件

OR

} else if (event.target.value == two || event.target.value == three || event.target.value == four) {
var colors = {
  one: '#67D986',
  two: '#f00',
  three: '#f00',
  four: '#f00'
};

$('#drop-down').on('change', function(e) {
  var value = $('option:selected').val();
  $('option').css('color', '#000');

  if (!value) {
    alert("There has been an error!!!");
  } else {
    $('option:selected').css('color', colors[value]);
  }
});

答案 1 :(得分:0)

如果您愿意,请以jquery方式执行:

$(document).ready(function(){
    $("#drop-down").on("change",function(){
      var selectedVal = $(this).val();
      switch(selectedVal)
      {
          case "one": $(this).css("color","red")
          break;
          case "two": $(this).css("color","blue");
          break;
      }
    });
});

HTML

<select id="drop-down" >
       <option value="">--</option>
       <option value="one">one</option>
       <option value="two">two</option>
       <option value="three">three</option>
       <option value="four">four</option>
</select>

答案 2 :(得分:0)

嗨,我想你甚至可以通过css实现这一点,我只是在那里结账

select{
    margin:40px;
    color:#fff;
    text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
select option {
    margin:40px;
    background: rgba(0,0,0,0.3);
    color:#fff;
    text-shadow:0 1px 0 rgba(0,0,0,0.4);
}

select option[val="one"]{
    background: #67D986;
}

select option[val="two"],select option[val="three"],select option[val="four"]{
    background: #f00;
}
 <select id="drop-down">
    <option val="">-----------------</option>
    <option val="one">One</option>
    <option val="two">Two</option>
    <option val="three">Three</option>
    <option val="four">Four</option>
</select>

<强> Check By only CSS

相关问题