【问题标题】:Why is this JS function running when it shouldn't?为什么这个 JS 函数在不应该运行的时候运行?
【发布时间】:2021-07-10 10:57:57
【问题描述】:

好的,请原谅我可能犯的任何错误,因为我还是个初学者。

我正在尝试为网站创建一个下拉菜单。我确实设法让它在鼠标悬停时出现并在鼠标悬停时消失,但我想尝试为消失的部分添加超时;问题是,只要我将鼠标移到顶部“图库”部分之外,隐藏菜单的功能就会开始运行,即使我仍在“菜单”的范围内。

如果没有setTimeout 部分,我可以让它正常工作(即,只有当我从下拉菜单或始终可见的“图库”按钮鼠标移出时,菜单才会关闭),但是,一旦我添加了它,整个一旦我从顶部始终可见的“图库”按钮中移出鼠标,功能就会激活。

由于我使用的是 TailwindCSS,请原谅无数的课程。

HTML:

<header class="fixed w-full bg-green-300 z-20">
  <nav class="flex justify-between h-full items-center">
      <div class="flex">
          <a href="index.html" class="p-4 hover:bg-red-200">Home</a>
          <a href="About_us.html" class="p-4 hover:bg-red-200">About us</a>
          <!--This is the whole "menu"-->
          <div class="Gallery flex flex-col">
              <!--This is the top always-visible button-->
              <a href="Gallery.html" class="p-4 hover:bg-red-200">Gallery</a>
              <!--This is the drop-down menu that's currently hidden-->
              <div class="GalleryDropdown absolute flex flex-col bg-green-300 text-center mt-14 hidden">
                  <a href="Bouquet_and_personal_items.html" class="p-4 hover:bg-red-200">Bouquets</a>
                  <a href="Ceremonies.html" class="p-4 hover:bg-red-200">Ceremonies</a>
                  <a href="Misc_arrangements.html" class="p-4 hover:bg-red-200">Misc</a>
                  <a href="Receptions.html" class="p-4 hover:bg-red-200">Receptions</a>
              </div>
          </div>
          <a href="Contacts.html" class="p-4 hover:bg-red-200">Contacts</a>
      </div>
      <div class="flex">
          <a href="index.html" class="p-4 hover:bg-red-200">Dark</a>
      </div>
  </nav>
</header>

JS:

//Gallery dropdown

    //gallery nav button
    const gButton = document.querySelector('.gallery');
    //gallery dropdown menu
    const gDrop = document.querySelector('.GalleryDropdown');

    //gallery dropdown activate
    gButton.addEventListener('mouseover', () => {
        gDrop.classList.remove('hidden');
    });

    gButton.addEventListener('mouseout', () => {
        setTimeout( () => { 
            gDrop.classList.add('hidden');
        }, 500);
    });

【问题讨论】:

    标签: javascript html tailwind-css


    【解决方案1】:

    setTimeout 是一个 API(这意味着它将异步运行 - 仅当调用堆栈为空时),因此如果您想同步运行代码(意味着代码将从第一行到最后一行按顺序运行)你可以在Hidden css 类中使用transition-delay: 1s; 而不是setTimeout

    您可以尝试的其他方法是使用 .classList.toggle 切换类,而不是添加和删除它们。

    【讨论】:

      【解决方案2】:

      尝试增加时间。 0.5 s 看隐藏效果也不算多。

       setTimeout(function() {...}, 2000)
      

      这个时间以毫秒为单位。所以 500 = 0.5s

      【讨论】:

      • 这仍然不能解决我的问题;整个函数在不应该运行的时候开始运行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2013-08-18
      • 2019-10-25
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多