为什么选择with onfocus不工作在IE? [英] Why does select with onfocus not work in IE?

查看:100
本文介绍了为什么选择with onfocus不工作在IE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想突出显示一个带有背景颜色的select元素来表示,它是必须的。当用户通过点击菜单打开菜单,我想删除背景颜色,所以它看起来更好,更可读。这在火狐,Chrome甚至IE6工作正常,但在IE7& 8下拉不会在第一次点击时打开(或打开和关闭非常快),只有在第二次。

I want to highlight a select element with a background color to indicate, it is mandatory. When the user opens the menu by clicking on it, I want to remove the background color, so it looks nicer and is more readable. This works just fine in Firefox, Chrome and even IE6, but on IE7 & 8 the pulldown doesn't open on the first click (or is opened and closed very fast), only on the second.

<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>

如何解决这个问题?

推荐答案


经过一点测试后,我觉得IE不会打开下拉菜单,如果风格以任何方式修改。

After a little bit of testing, it appears to me that IE doesn't open the dropdown if the style is modified in any way.

是的,很好的bug捕获。任何改变选择框(包括任何样式的变化,甚至一个通过改变一个父类名称触发)使得IE重新创建操作系统部件,它有副作用关闭它。所以下拉列表打开,但在渲染之前立即关闭。

Yeah, good bug catch there. Anything that changes the select box (including any style change, even one triggered by changing a parent className) makes IE recreate the OS widget for it, which has the side-effect of closing it. So the dropdown is opened, but immediately closed before rendering. If you put a timeout on the background change function you can see it happen afterwards.

你需要的只是在聚焦之前的事件,所以你可以改变风格,导致下拉列表关闭,在它打开之前。幸运的是,有一个!但它只有IE。对于其他浏览器(包括IE8),最好坚持简单的CSS :focus selector:

What you would need would be an event first just before focusing, so you can change the style, causing the dropdown to close, before it opens. Luckily, there is one! But it's IE-only. For other browsers (including IE8), best stick to the simple CSS :focus selector:

<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]-->

这篇关于为什么选择with onfocus不工作在IE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆