为什么使用onfocus选择在IE中不起作用?

Tim*_*the 2 html javascript css internet-explorer

我想突出显示一个带有背景颜色的选择元素,这是强制性的.当用户通过单击打开菜单时,我想删除背景颜色,因此它看起来更好,更具可读性.这在Firefox,Chrome甚至IE6中都可以正常工作,但在IE7和8上,下拉时不会打开下拉(或者打开和关闭非常快),仅在第二次打开时.

<select 
    style="background-color: #BDE5F8"
    onfocus="this.style.backgroundColor='#fff'"
    onblur="this.style.backgroundColor='#BDE5F8'">
    <option>choose...</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

bob*_*nce 6

经过一些测试后,在我看来,如果以任何方式修改样式,IE都不会打开下拉列表.

是的,那里有好虫.任何更改选择框的内容(包括任何样式更改,甚至是通过更改父类名称触发的更改)都会使IE为其重新创建操作系统小部件,这会产生关闭它的副作用.因此下拉列表打开,但在渲染之前立即关闭.如果你在后台更改功能上设置超时,你可以看到它在之后发生.

在聚焦之前,您需要的是一个事件,因此您可以在打开之前更改样式,使下拉列表关闭.幸运的是,有一个!但它只是IE浏览器.对于其他浏览器(包括IE8),最好坚持使用简单的CSS :focus选择器:

<style>
    select { background-color: #BDE5F8; }
    select:focus, select.focus { background-color: white; }
</style>
<select>
        <option>choose...</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
</select>

<!--[if lt IE 8]><script>
    // Fix lack of :focus selector for select elements in IE7-
    //
    var selects= document.getElementsByTagName('select');
    for (var i= selects.length; i-- >0;) {
        var select= selects[i];
        select.onfocusin= function() {
            this.className= 'focus';
        };
        select.onfocusout= function() {
            this.className= '';
        };
    }

    // Or, the same expressed in jQuery, since you mentioned using it
    //
    $('select').bind('focusin', function() {
        $(this).addClass('focus');
    }).bind('focusout', function() {
        $(this).removeClass('focus');
    });
</script><![endif]-->
Run Code Online (Sandbox Code Playgroud)