gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:09 25 4
gpt4 key购买 nike

我想用背景色高亮一个select元素来表示,这是强制性的。当用户通过单击打开菜单时,我想删除背景颜色,这样它看起来更漂亮并且更具可读性。这在 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>

我该如何解决这个问题?

最佳答案

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 catch。任何更改选择框的内容(包括任何样式更改,甚至是通过更改父类名触发的更改)都会使 IE 为其重新创建操作系统小部件,这会产生关闭它的副作用。所以下拉菜单被打开,但在渲染之前立即关闭。如果您在后台更改功能上设置超时,您可以看到它会在之后发生。

您需要的是在聚焦之前首先发生一个事件,这样您就可以更改样式,使下拉列表在打开之前关闭。幸运的是,there is one !但它仅限于 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]-->

关于javascript - 为什么选择 onfocus 在 IE 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1763113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com