Heim > Fragen und Antworten > Hauptteil
Ich habe ein Dropdown-Menü erstellt, das erfolgreich umschaltet, aber es scheint nur die erste Klasse auszuwählen, und wenn ich auf das zweite Dropdown-Menü klicke, wird der Inhalt des ersten Dropdown-Menüs umgeschaltet. Vermisse ich hier etwas? Das ist mein Code:
const menuListDropdown = document.querySelectorAll('.menu-block-dropdown'); const menuBlock = document.querySelector('.menu-block'); menuListDropdown.forEach((menuBlockList) => { menuBlockList.addEventListener('click', function() { menuBlock.classList.toggle('menu-block-active'); }) })
.menu-block { background: #fff; box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px; padding: 15px; border-radius: 8px; position: absolute; top: 35px; opacity: 0; transition: 150ms ease; } .menu-block-active { transition: 150ms all; opacity: 1; } .menu-block-list { display: flex; flex-direction: column; gap: 15px; } .menu-block-list a { color: #444444; margin: 0 0 0.25 0; padding: 0; font-weight: 500; }
<li class="menu-block-dropdown"> <a href="#">Resources</a> <div class="menu-block"> <div class="menu-block-list"> <a href="#">Dropdown 1</a> <a href="#">Dropdown 2</a> </div> </div> </li> <li class="menu-block-dropdown"> <a href="#">Blogs</a> <div class="menu-block"> <div class="menu-block-list"> <a href="#">Dropdown 3</a> <a href="#">Dropdown 4</a> </div> </div> </li>
P粉1419112442024-02-27 00:56:42
问题是,您只选择了一个下拉列表。因此,需要做的是选择与您单击的菜单链接相关的下拉列表。
请参阅下面我在 JS
中进行的更改
const menuListDropdown = document.querySelectorAll('.menu-block-dropdown'); // Not needed // const menuBlock = document.querySelector('.menu-block'); menuListDropdown.forEach((menuBlockList) => { menuBlockList.addEventListener('click', function() { // Select the Block within the Target List const menuBlock = menuBlockList.querySelector(".menu-block"); menuBlock.classList.toggle('menu-block-active'); }) })
.menu-block { background: #fff; box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px; padding: 15px; border-radius: 8px; position: absolute; top: 35px; opacity: 0; transition: 150ms ease; } .menu-block-active { transition: 150ms all; opacity: 1; } .menu-block-list { display: flex; flex-direction: column; gap: 15px; } .menu-block-list a { color: #444444; margin: 0 0 0.25 0; padding: 0; font-weight: 500; } li { display: inline-block; }