3

我在这里做的很简单:

当有人从选择中选择一个选项时,我想将该选择的背景颜色更改为所选选项颜色。

$("select").change(function(){
    var newcolor=$(this).children("option:selected").css("background-color");
    $(this).css("backgroundColor", newcolor);
});

容易吧?好吧,它在 Firefox 17.0.1 中根本不起作用(它在 Chrome 中起作用)。问题是变量 newcolor 被填充:rgb(51, 153, 255)。最好的部分是在我的代码、css 或任何东西中都找不到这种颜色。

我已经尝试更改background-colorbackgroundColor, childrento find,但没有任何效果。

有趣的是,如果我这样做:

$("select").change(function(){
    var newcolor=$(this).children("option:first").css("background-color");
    $(this).css("backgroundColor", newcolor);
});

并选择第一个选项,而不是选定的...它有效!

我可能可以使用一些类使其工作,但我很好奇,为什么会发生这种情况,有什么办法可以解决它?

编辑:添加了jsFiddle。用 chrome 和 firefox 试试吧!

4

1 回答 1

1

发生这种情况是因为选择一个选项会更改其背景颜色。您可以在选择它时看到它。之所以这样做,是因为用户代理样式表中有一条规则,该规则使用“选定选项”背景颜色和颜色设置选定选项的样式。

于 2012-12-14T09:25:37.430 回答