2010-12-03 64 views
3

問候, 有一個這樣的選擇框:jQuery的:選擇選項和背景顏色

<select id="events"> 
    <option value="1" style="background-color:green;">Event 1</option> 
    <option value="2" style="background-color:yellow;">Event 2</option> 
    <option value="3" style="background-color:blue;">Event 3</option> 
    <option value="4" style="background-color:red;">Event 4</option> 
</select> 

初始瀏覽器渲染這個選擇框和每一個選擇完成時間,我想選擇框「事件」來獲取所選選項的背景顏色。

這怎麼能通過jquery或通過常規的JavaScript來實現?

+0

可以使用$(「表單選項」)來代替ID嗎?或者某種方法讓所有選擇菜單的樣式都相同? – 2011-11-01 20:49:55

回答

2
//Alert color on initial page load 
var bkg = $("#events option:selected").css("background-color"); 
    alert(bkg); 

//Handle change event and alert color when selection is done 
$(function(){ 
$("#events").change(function() { 
    var bkg = $("#events option:selected").css("background-color"); 
    alert(bkg); 
}); 
}); 
1

selected

$('#events').bind('change', function() { 

    var bgc = $(this).find('option:selected').css('background-color'); 

}); 
1

你可以這樣做:

$("#events").change(function() { 
    $(this).css("backgroundColor", 
     $(this).find(":selected").css("backgroundColor") 
    ); 
}).change(); 

You can test it out here但是,這不適用於所有的瀏覽器,特別是在IE中,<select>元素是非常不可靠的(因爲沒有更好的...或真正的詞)。它將在支持它的瀏覽器中工作,並且在沒有的瀏覽器中不起作用。您可以等待在所有瀏覽器中設置父元素的樣式以提供指示符something like this

+0

你的第一個代碼在firefox中不起作用。相反,我建議完全像`style`這樣的屬性 - http://jsfiddle.net/qEPPC/2/ – rickyduck 2012-12-12 14:02:42

0

IE友好的方式,這必須適用於option標記。

$(this).html($(this).html());