javascript - 切换元素 onblur 和 onclick 的可见性
问题描述
我有一个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/
我尝试签event.explicitOriginalTarget
入该功能(如果事件的目标不是切换,则onblur
在线隐藏),该功能适用于 Firefox,但不适用于 Chrome。select
onblur
那么这样做的正确方法是什么?
解决方案
我自己找到了解决方案,也看到了这个相关的问题。
这个想法是向切换添加mousedown
和mouseup
事件。那么执行顺序将是
(1)toggle.onmousedown
(2) 选择.onblur
(3)toggle.onmouseup
(4)toggle.onclick
也就是说,在mousedown
/mouseup
事件中,我们可以设置和重置忽略标志;然后,该标志将仅在 中设置onblur
,在中onclick
它已经被重置。
所以我们得到了
document.getElementById('toggle').onclick = function () {
var select = document.getElementById('select');
select.style.display = select.style.display === 'none' ? 'inline' : 'none';
select.focus();
};
document.getElementById('toggle').onmousedown = function () {
document.getElementById('select').ignoreClickEvent = true;
};
document.getElementById('toggle').onmouseup = function () {
document.getElementById('select').ignoreClickEvent = false;
};
document.getElementById('select').onblur = function () {
if (!this.ignoreClickEvent) {
this.style.display = 'none';
}
};
推荐阅读
- html - 如果路径在 MongoDB 中,在哪里存储 IMG 文件?
- watchkit - 使用渲染模式“模板”(CLKComplicationTemplateGraphicCircularClosedGaugeImage)时,TintColor 不适用于我的复杂功能
- c# - mstest 的 DataSource 属性的 .Net 核心替代方案是什么?
- ios - iOS:定期(或不定期)执行代码
- powershell - 如何使用powershell在Notes字段中附加文本
- ios - 切换应用 iOS 无法更改默认启动图标
- sql - SQL Server 为列中的每个不同值创建一个 ID
- python - 使用 pybind11 通过预先存在的嵌入式 python 解释器公开 C++ 功能
- javascript - 如何模拟长按或右键单击 Javascript
- c++ - 使用插入成员函数将范围插入空向量是否合法?