好吧,所以,请原谅我可能犯的任何错误,因为我还是一个初学者。
我正在尝试做的是为网站创建一个下拉菜单。我确实设法让它出现在鼠标上方,并在鼠标移出时消失,但我想尝试为消失的部分添加一个超时;问题是,只要我将鼠标移出顶部的“画廊”部分,隐藏菜单的功能就会开始运行,即使我仍然在“菜单”的范围内。
我可以让它在没有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);
});发布于 2021-04-15 20:17:12
试着增加时间。0.5秒看不到隐藏的效果。
setTimeout(function() {...}, 2000)这一次是在milisecods。所以500 =0.5秒
发布于 2021-04-15 20:40:23
setTimeout是一个应用程序接口(这意味着它将异步运行-只有当调用栈为空时),所以如果您想同步运行代码(这意味着代码将从第一行到最后一行按顺序运行),您可以在Hidden css类中使用transition-delay: 1s;,而不是setTimeout。
您可以尝试的另一件事是使用.classList.toggle切换类,而不是添加和删除它们。
https://stackoverflow.com/questions/67107896
复制相似问题