5

鉴于这个简单的html,

<select id="ddl">
    <option style="background:#0f0">a</option>       
    <option style="background:#f00;">b</option>   
    <option>c</option>
</select>

( http://jsfiddle.net/DxK47/ ) 你可以看到每个选项都有它自己的背景颜色。

Unfortunately, when whatever option is selected (causing the dropdownlist to 'close'), the background remains white (or whatever the page default is).

选择后是否可以在下拉列表中显示所选项目的背景(理想情况下不使用javascript)

4

5 回答 5

3

是的,有可能

JS:

$(function(){
    $("#ddl").on("change", function(){
        $("#ddl").css("background", $("#ddl option:selected").attr("style").replace("background:",""));
    });       
});

jsfiddle: http://jsfiddle.net/SnakeEyes/DxK47/3/

and remove the ; from second option

<option style="background:#f00;">b</option>

to

<option style="background:#f00">b</option>  

Other solution: http://jsfiddle.net/SnakeEyes/DxK47/13/

于 2012-09-26T12:35:23.653 回答
2

您可以使用选择的库来做到这一点

Chosen 是一个 JavaScript 插件,它使长而笨重的选择框更加用户友好。它目前有 jQuery 和 Prototype 两种风格。

于 2012-09-26T12:33:47.770 回答
1

When CSS4 introduces the parent selector it may be possible, but for now there is no way to style a parent based on its children. In the meantime, here is a simple JS solution:

$("#ddl").change(function () {
   $(this).css('background-color', $(this).find(":selected").css('background-color'));
});

NOTE: this requires all of the <option> to have a specified background color even if it's white. That's pretty simple to do with JS too if you don't feel like it otherwise.

于 2012-09-26T12:35:54.620 回答
1

This can be easily done with a little bit of JavaScript. I made you a small example at JSFiddle: http://jsfiddle.net/DxK47/84/

I used jQuery here, I leave it to you as an exercise to do a similar trick with other js frameworks or even pure js if that's what you want.

$("#ddl").change(function(evt) {
  var select = evt.currentTarget;
  var item = select.item(select.selectedIndex);
  var style = $(item).attr("style");
  if (style) {
    $("#ddl").css({"background-color": style.substring(11)});
  } else {
    $("#ddl").css({"background-color": ""});
  }
});

Edit: I was too slow (and not a jQuery expert), look at above answers for more brief examples that do basically the same.

于 2012-09-26T13:29:52.707 回答
-1

This syntax will work in XHTML and does not work in IE6, but this is a non-javascript way, as you requested:

option[selected] { background: #f00; }

If you want to do this on-the-fly, then you would have to go with javascript, the way others have suggested....

于 2012-09-26T12:45:10.213 回答