Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中单击关闭下拉导航栏?_Javascript_Html_Bulma - Fatal编程技术网

在JavaScript中单击关闭下拉导航栏?

在JavaScript中单击关闭下拉导航栏?,javascript,html,bulma,Javascript,Html,Bulma,我已经使用Bulma实现了一个导航栏,但是在用户单击导航栏中的元素后,我很难关闭它。我有一个单独的页面设置,因此页面不会刷新,因此导航栏不会“重置”并关闭 很抱歉,如果答案是显而易见或简单的,我对JavaScript非常陌生。我在下面附上了一段代码 document.addEventListener('DOMContentLoaded', () => { // Get all "navbar-burger" elements const $navbarBurgers = A

我已经使用Bulma实现了一个导航栏,但是在用户单击导航栏中的元素后,我很难关闭它。我有一个单独的页面设置,因此页面不会刷新,因此导航栏不会“重置”并关闭

很抱歉,如果答案是显而易见或简单的,我对JavaScript非常陌生。我在下面附上了一段代码

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');

        });
      });
    }
});

任何帮助都将不胜感激,谢谢

当元素被添加到DOM(在您的例子中是
.navbar burger
s)时,您需要重新连接侦听器。您可以将上述javascript封装在一个函数中,并在站点内容发生更改时再次调用它

或者指定一个侦听单击事件的父元素,并检查其中单击的目标是否具有类
.navbar burger
。例如:

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

    if (document.querySelector('.navbar-burger')) {
        document.querySelector('body').addEventListener('click', (el) => {
            if (el.currentTarget.classList.contains('.navbar-burger')) {
                // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
                el.classList.toggle('is-active');
                document.getElementById(el.getAttribute('data-target')).classList.toggle('is-active');
            }
        });
    }

});

在本例中,我指定了
body
,但我建议您更具体一些。因为每次点击你的网站都会进入这个事件,并检查它是否是一个导航的东西。但是,重新附加侦听器的第一个选项是更好的实践。

const$navbarBurgers=Array.prototype.slice.call(document.querySelectorAll('.navbar burger'),0)=>
导航如何正常打开和关闭的浏览器都可以编写
const$navbarBurgers=[…document.querySelectorAll('.navbar burger')]
。@mplungjan我认为navbar元素中添加了一个“is active”类(来自Bulma)。因此,解决方案可能是在单击元素后删除“是活动的”?如果可能的话。对不起,我根本不认识布尔玛