简体   繁体   中英

open/close as if hovering the menu one by one (javascript)

I have an issue i'm trying to figure out. I have a drop-down menu that appears when we hover the nav. I'm trying to build a code that when executed opens up every drop-down one by one and then closes it as if we would hover the first one and then go to the next and so on. I used the setTimeout() which works when it displays the dropdown but i have no idea how to make the displayed drop-down disappear after the code goes to the next one.

update: I am referring to this site: https://www.laithwaites.co.uk/product/The-Insider 's-Collection/M0498501

here's my code:

const navBar = document.querySelectorAll('.sub-menu.pad-10');// takes the class of all the dropdowns (same class)

  window.setTimeout((str) => {
for(let i=0;i<str.length;i++){
      str[i].style.display = 'block';
    }
  }, 5000, navBar);

Well, as you didn't show your HTML, I improvised with a simple code just to demonstrate some logic that you can use. If you want to show things in a sequence, one after another, you need to increase your timer and after it shows, add another timer inside to make it disappear.

Look the code below and try to get the logic, you can use it to make what you need, not necessarly exact the same as I did, but it's a good starting point.

(Obs.: I made a function that do this behavior, and I'm calling it with setInterval() , don't use this (the setinterval), I'm only making it to demonstrate the function without stoping, but it's not a good practice)

 const navBar = document.querySelectorAll('.sub-menu'); function showSubMenus(){ var timer = 500; for (var i = 0; i < navBar.length; i++){ var nav = navBar[i]; setTimeout(function(nav){ nav.style.display = 'block'; setTimeout(function(nav){ nav.style.display = 'none'; }, 1000, nav); }, timer, nav); timer = timer + 1500; } } showSubMenus(); setInterval(showSubMenus, 8500); 
 div{ border: 1px solid black; margin: 10px; } .sub-menu{ display:none } 
 <div style='display: inline-block'>Menu 1 <div class='sub-menu'>Sub Menu 1 </div> </div> <div style='display: inline-block'>Menu 2 <div class='sub-menu'>Sub Menu 2 </div> </div> <div style='display: inline-block'>Menu 3 <div class='sub-menu'>Sub Menu 3 </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM