Can I select a style element so that the style of the selected parameter is displayed when the "closed" drop-down menu is displayed?

Given this simple html,

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

( http://jsfiddle.net/DxK47/ ) You can see that each parameter has its own background color.

Unfortunately, when a parameter is selected (as a result of which the drop-down list "closes"), the background remains white (or whatever the default value of the page).

Is it possible for the background of the selected item to appear in the drop-down list after selection (ideally without using javascript).

+5
source share
5 answers

Yes maybe

JS:

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

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

;

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

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

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

+3

, Chosen

JavaScript, , . jQuery, .

+2

CSS4 , , . , JS:

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

: , <option> , . JS, .

+1

JavaScript. JSFiddle: http://jsfiddle.net/DxK47/84/

jQuery , , js- js, .

$("#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": ""});
  }
});

: ( jQuery), , .

+1

XHTML IE6, -javascript-, :

option[selected] { background: #f00; }

" ", javascript, ...

-1

All Articles