简体   繁体   中英

IE11 not applying CSS class to first Option element of Select dropdown

A certain .aspx page renders a simple SELECT list with various OPTIONs . Some, but not all, of these OPTION elements will have a special style class applied to render them in a different color to reflect a particular distinct status.

Ultimately, this works, with a single frustrating exception. If the first OPTION within the SELECT is given the CLASS designation, IE11 will not render that option with the color specified in the corresponding CSS rule. When viewing the page within the IE11 dev tools, it appears that the rule is being applied, yet, visually, it isn't. If the particular OPTION appears as any other item in the SELECT , the rule works.

The solution at hand, a snippet of which is provided below, was modeled after a seemingly very similar case presented here: How to change the text color of first select option

<style>
select {color: black;}
select option {color: black;}
select option.specialStatus{
    color: red;
}
select option.specialStatus:first-child{
    color: red;
}
</style>
..
<select>
    <option class='specialStatus' value=1>Hi</option>
    <option value=2>Bye</option>
</select>

The intent, in effect, is to say "render this SELECT with OPTIONs ordinarily in black, unless they are given the 'specialStatus' class. When 'specialStatus' is present, render the OPTION in red. The 'first-child' rule was an effort to overcome any default styling that may be present.

Oddly enough, this styling works 100% of the time in old, nasty IE8 - this behavior of the first OPTION not being honored is seen only in IE11. That's why the subject solution linked above seemed the obvious choice - it works, but obviously something in conjunction with the class designations is causing a problem. Help would be most appreciated in diagnosing exactly what's wrong.

Adding to my comment, the problem is that the select color is making the Hi value black when selected. To make it work, you'll need JavaScript. I updated @YuriyGalanter's fiddle to include the necessary JavaScript:

function changeSelectClass(e) {
    this.classList.remove('specialStatus');
    if (this.options[this.selectedIndex].className.indexOf('specialStatus') !== -1) {
        this.classList.add('specialStatus');
    }
}
document.getElementsByTagName('select')[0].onchange = changeSelectClass;
changeSelectClass.call(document.getElementsByTagName('select')[0]);

and CSS:

select { color: black; }
option { color: black; }
select.specialStatus, option.specialStatus { color: red; }

You could make it more generic by applying the same class(es) to the select as were applied to the option , but this answers the specific question asked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM