javascript jquery:选择选项和背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4345042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: select options and background color
提问by Hellnar
Greetings, Having a such select box:
问候,有这样的选择框:
<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>
At the initialbrowser render of this selectbox and each time a selection is done, I want the selectbox "events" to get the background-color of the selected option.
在此选择框的初始浏览器呈现以及每次完成选择时,我希望选择框“事件”获得所选选项的背景颜色。
How can this be achieved via jquery or via regular javascript ?
这如何通过 jquery 或常规 javascript 实现?
采纳答案by Serge Zab
//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);
});
});
回答by andres descalzo
回答by Nick Craver
You can do this:
你可以这样做:
$("#events").change(function() {
$(this).css("backgroundColor",
$(this).find(":selected").css("backgroundColor")
);
}).change();
You can test it out here. But, this won't work in all browsers, especially in IE the <select>element is notoriously unstyleable (for lack of a better...or real word). It'll work in the browsers that support it and just have no effect in the ones that don't. You may instead wait to style a parent element to give an indicator in all browsers, something like this.
你可以在这里测试一下。 但是,这并不适用于所有浏览器,尤其是在 IE 中,该<select>元素是出了名的缺乏样式(因为缺少更好的……或真实的词)。它将在支持它的浏览器中工作,而在不支持它的浏览器中不起作用。您可以改为等待为父元素设置样式以在所有浏览器中提供指示符,例如.
回答by Nick Craver
IE friendly way, this has to applied to optiontag.
IE 友好的方式,这必须应用于option标记。
$(this).html($(this).html());

