获取一个下拉菜单以在汉堡菜单的内部/外部工作

时间:2019-03-25 22:38:22

标签: javascript html mobile drop-down-menu hamburger-menu

我想让“语言”菜单在桌面上时可以用作下拉菜单,而在移动设备上时保持为非活动下拉菜单。

点击移动设备后,它应该会在下拉菜单中显示这些选项,而这些选项仍保留在汉堡菜单中。

语言菜单:

https://i.imgur.com/1vCEc2C.png

&&

https://i.imgur.com/R4AKUDG.png

我希望它在台式机上做什么:

https://i.imgur.com/8jFIVi5.png

我已经使用JavaScript代码在桌面上点击了菜单,但是在移动设备上,菜单的行为很奇怪。

在桌面上单击时,我希望下拉菜单起作用,并且在桌面上其他任何地方单击时,下拉菜单都会关闭,而不仅仅是单击菜单本身。

在移动设备上,菜单显示异常,而不是在单击之前被禁用。

JSFiddle-> <script async src="//jsfiddle.net/jkuwg3ac/embed/"></script>

1 个答案:

答案 0 :(得分:0)

没有 JavaScript 的情况下,有一种使用布尔玛创建语言菜单的更好的方法。

语言菜单 HTML

<div class="select">
  <select>
    <option selected>English</option>
    <option>Italian</option>
    <option>Arabic</option>
  </select>
</div>

这是您使用我的想法进行的项目:

document.addEventListener('DOMContentLoaded', () => {

  // Get all "navbar-burger" elements
  const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);

  // Check if there are any navbar burgers
  if ($navbarBurgers.length > 0) {

    // Add a click event on each of them
    $navbarBurgers.forEach(el => {
      el.addEventListener('click', () => {

        // Get the target from the "data-target" attribute
        const target = el.dataset.target;
        const $target = document.getElementById(target);

        // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
        el.classList.toggle('is-active');
        $target.classList.toggle('is-active');

      });
    });
  }

});
  
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test!</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css">
  <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
</head>

<body>


  <nav class="navbar has-text-centered" role="navigation" aria-label="main navigation">
    <div class="navbar-brand">
      <a class="navbar-item" href="https://bulma.io">
        <img src="https://bulma.io/images/bulma-logo.png" width="112" height="28">
      </a>

      <a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="navMenu">
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
      </a>
    </div>

    <div id="navMenu" class="navbar-menu">
      <div class="navbar-start">
        <a class="navbar-item">
            Home
          </a>

        <a class="navbar-item">
            Documentation
          </a>

      </div>

      <div class="navbar-end">
        <div class="select">
          <select>
            <option selected>English</option>
            <option>Italian</option>
            <option>Arabic</option>
          </select>
        </div>

      </div>


    </div>
  </nav>

</body>

</html>