【问题标题】:dropdown with backgrounds as option show selected带有背景的下拉菜单作为选项显示已选择
【发布时间】:2015-07-09 19:38:36
【问题描述】:

我有不同背景的下拉菜单,例如红色、蓝色和绿色。

我希望当有人选择绿色时,它会变成绿色,就像这样。我该怎么做?

下面是我的html代码:

<select name="mcolor" class="form-control" id="mcolor">
  <option value="">-- select color --</option>																				         <option value="#ff0000" style="background-color:#ff0000">&nbsp;</option>						
  <option value="#ffffff" style="background-color:#ffffff">&nbsp;</option>														</select>

【问题讨论】:

标签: jquery html css


【解决方案1】:

这是在选择时更改背景颜色的方法:

$("#mcolor").change(function(){
    $('body').css("background-color", $(this).val());
});

JSFiddle demo here

【讨论】:

    【解决方案2】:

    function colourFunction() {
    var myselect = document.getElementById("select1"),
    colour = myselect.options[myselect.selectedIndex].className;
    myselect.className = colour;
    myselect.blur(); 
    }
    #select1 {width:150px; color:rgba(0, 0, 0, 0);}
    #select1:focus, #select1:focus {
    color:black;
    }
    .white {background:white;}
    .red {background:red;}
    .yellow {background:yellow;}
    .green {background:green}
    <select id="select1" onchange="colourFunction()">
    <option class="white" value="A">This should have a WHITE background</option>
    <option class="red" value="B">This should have a RED background</option>
    <option class="yellow" value="C">This should have a YELLOW background</option>
    <option class="green" value="D">This should have a GREEN background</option>
    </select>

    【讨论】:

    • 这里我只给选择。
    【解决方案3】:

    试试这个

        $('.form-control').on('change', function() {
          $(this).css('background-color', $(this).val());
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="mcolor" class="form-control" id="mcolor">
            <option value="red">-- red --</option>  
            <option value="green">-- green --</option>  
            <option value="black">-- black --</option>  
            </select>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2021-03-07
      相关资源
      最近更新 更多