【发布时间】:2020-02-19 23:32:33
【问题描述】:
我有一个div 元素用作切换开关,还有一个select 元素应以如下方式显示/隐藏:
(1) 当点击切换时,select 将被显示并聚焦,如果它被隐藏了
(2) 当点击切换时,select 应该被隐藏,如果它是可见的
(3) When the select looses focus, it shall be hidden.
当select 具有焦点并且用户单击切换时,现在出现了这种边缘情况——然后onclick 和onblur 这两个事件被触发并相互取消,至少在Firefox 中:
<div id="toggle">toggle</div>
<div>foobar</div>
<select id="select" multiple>
<option>foo</option>
<option>bar</option>
</select>
document.getElementById('toggle').onclick = function () {
var select = document.getElementById('select');
select.style.display = select.style.display === 'none' ? 'inline' : 'none';
select.focus();
};
document.getElementById('select').onblur = function () {
this.style.display = 'none';
};
https://jsfiddle.net/2wrxykpd/
我尝试在onblur 函数中检查event.explicitOriginalTarget(如果onblur 事件的目标不是切换,则在线隐藏select),这在Firefox 中有效,但在Chrome 中无效。
那么正确的方法是什么?
【问题讨论】:
标签: javascript onclick event-handling onblur