从选项卡中退出后,关闭<div>

时间:2019-01-18 14:43:32

标签: javascript keyboard accessibility keyboard-events

我有一个面板,其中包含单击按钮即可打开的列表:

<button id="menuButton">Menu</button>
<div id="menuPanel">
    <ul>
        <li>Name</li>
        <li>Role</li>
        <li>Profile</li>
        <li>Management</li>
    </ul>
</div>

按钮单击使用JavaScript将CSS类添加到中以显示它。对于键盘用户,如果他们跳过。中的最后一个元素,我希望能够删除该类。

JavaScript:

(function ready(fn) {
    if (document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);

        let panel = document.getElementById('menuPanel'),
            button = document.getElementById('menuButton');

        button.onclick = checkPanelOn;

        function checkPanelOn(e) {

            e.preventDefault();
            if (panel.classList.contains('on')) {
                panel.classList.remove('on');
            } else {
                panel.classList.add('on');
            }
        }
    }
}());

我正在寻找一个纯JavaScript解决方案(对不起,不能在该项目上使用jQuery),但我一直在努力寻找答案。你有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这是一种使用tabindexfocusout的方法:

let panel = document.getElementById('menuPanel'),
  button = document.getElementById('menuButton');

button.onclick = checkPanelOn;

panel.addEventListener('focusout', function(event) {
  if (panel.contains(event.relatedTarget)) {
    return;
  }
  checkPanelOn(event);
});

function checkPanelOn(e) {

  e.preventDefault();
  if (panel.classList.contains('on')) {
    panel.classList.remove('on');
  } else {
    panel.classList.add('on');
  }
}
.on {
  display: none;
}
<button id="menuButton">Menu</button>
<div id="menuPanel">
  <ul>
    <li tabindex="0">Name</li>
    <li tabindex="0">Role</li>
    <li tabindex="0">Profile</li>
    <li tabindex="0">Management</li>
  </ul>
</div>
<button>Outside button</button>

JSFiddle:https://jsfiddle.net/nzmtL1od/