将css应用于下拉选项元素

时间:2015-04-28 18:36:45

标签: jquery html css internet-explorer-11

我有一个简单的下拉列表: -

<select id="fruits">
    <option value="-1">Select</option>
    <option value="1">Banana</option>
    <option value="2">Apple</option>
    <option value="3">Grapes</option>
</select>

我正在尝试使用jQuery .css属性为其中一个选项设置自定义样式,但它在任何IE11 \ Firefox中都没有按预期工作。这是我的jQuery代码: -

$("#fruits").change(function () {
    $(this).css("background-color", "transparent");
    $(this).find('option').css("background-color", "transparent");
    var selectedVal = $(this).find('option:selected');
    if (selectedVal != "-1")
    {
       console.log("B4->" + $(this).find('option:selected').css("background-color"));
       $(this).find('option:selected').css("background-color", "#BEF781");
       console.log("Aftr->" + $(this).find('option:selected').css("background-color"));
    }
});

此代码的问题是它正在更新DOM(我已经使用开发人员工具和firebug验证了它),但是当我尝试获取background-color的值时,它给了我旧值ie {{ 1}}而不是rgb(51, 153, 255)也不是在IE11中更新颜色。之前这段代码在IE7中工作得很好,但是我想让它在rgb(190, 247, 129)中工作?我该怎么办?

P.S。 - 这在JSFiddle中运行正常,我已经对此进行了修改,但我希望这可以在IE11中运行。

2 个答案:

答案 0 :(得分:0)

选择框和子选项的样式在不同的浏览器中仅提供有限的支持。 Firefox允许您在选项中设置字体样式,Chrome允许您设置整个列表的样式,但如果我没记错的话,则不允许单独选项。有关详细信息,请参阅this article。您可以将其他元素设置为按照您想要的方式显示,然后编写javascript以像选择一样操作。

答案 1 :(得分:0)

为了在浏览器中实现外观和样式的一致性,我建议您使用jQuery UI selectMenu小部件。要使用此功能,您只需执行以下操作:

在您的HTML中(与以前几乎相同):

    <select id="fruits" style="width: 200px;">
        <option value="-1">Select</option>
        <option value="1">Banana</option>
        <option value="2">Apple</option>
        <option value="3">Grapes</option>
    </select>

在标题中:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

在您的自定义脚本中:

$(document).ready(function () {
    $("#fruits").selectmenu({
        select: function (event, ui) {

            // Make all the list items transparent.
            $(".ui-selectmenu-menu li.ui-menu-item").css("background-color", "transparent");

            // Make the SELECTED list item have a green background.
            $(".ui-selectmenu-menu li.ui-menu-item:nth-child(" + (ui.item.index + 1) + ")").css("background-color", "#BEF781");
        }
    });
});