首页 > 解决方案 > 切换元素 onblur 和 onclick 的可见性

问题描述

我有一个div用作切换的select元素,以及一个应该以如下方式显示/隐藏的元素:

(1)点击切换时select,如果隐藏,则应显示并聚焦

(2) 单击切换时select,如果可见,则应隐藏

(3) When the select looses focus, it shall be hidden.

现在有这种边缘情况,当select有焦点并且用户点击切换时——然后两个事件,onclickonblur,被触发并相互取消,至少在 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。selectonblur

那么这样做的正确方法是什么?

标签: javascriptonclickevent-handlingonblur

解决方案


我自己找到了解决方案,也看到了这个相关的问题

这个想法是向切换添加mousedownmouseup事件。那么执行顺序将是

(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';
  }
};

https://jsfiddle.net/ezt0sonj/


推荐阅读