单击页面上的任意位置时如何关闭下拉菜单 (javascript)

How can I make my dropdown menu close when clicking anywhere on the page (javascript)

我制作了一个下拉列表,当用户单击输入字段时会打开,但是我希望能够删除活动的 class,这样当用户单击页面上的其他任何地方时下拉列表就会消失。这是我的代码:

// menu dropdown
    const searchInput = document.querySelector('.search-input');
    const dropdown = document.querySelector('.dropdown-container');

    searchInput.addEventListener('click', () => {
      dropdown.classList.add('dropdown-container--active')
    })

    window.addEventListener('click', function(e) {
      if (!searchInput.contains(e.target) && (!dropdown).contains(e.target)) {
        dropdown.classList.remove('dropdown-container--active')
      }
    })
        <ul>
          <li>
            <input data-target="volts" type="text" placeholder="Volts" class="search-input">
            <ul class="dropdown-container">
              <h5 class="volt-options-title">Top Searches</h5>
                <li>
                  <a href="#" class="volt-options">6</a>
                </li>
                <li>
                  <a href="#" class="volt-options">12</a>
                </li>
                <li>
                  <a href="#" class="volt-options">24</a>
                </li>
                <li>
                  <a href="#" class="last-link">48</a>
                </li>
            </ul>
          </li>
        </ul>

您可以利用 focusout 事件。添加侦听器并在用户离开搜索输入时删除 active class。如下图:

searchInput.addEventListener('focusout', (event) => {
  dropdown.classList.remove('dropdown-container--active')
});