我已經製作了一個可以成功切換的下拉列表,但它似乎只選擇了第一個類,當我單擊第二個下拉列表時,它會切換第一個下拉列表的內容。我在這裡缺少什麼嗎?這是我的程式碼:
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; }