选择某个项目时关闭下拉菜单

问题描述 投票:0回答:1

我的网页 m1maths.com 有一个带有下拉菜单的导航栏。我希望在选择某个项目时关闭菜单,但他们没有。下面复制了导航栏代码的精简版本。有一个带有一些 javascript 的 html 文件,用于关闭菜单,然后是 css 文件。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>navbar</title>
<link rel="stylesheet" href="navbar.css">
</head>
<body>

<table width="1000" border="0" align="center"><tbody bgcolor="#000"><tr><td>

    <div class="navbar">   
      <ul class="dd"> 
       
           <li><div class="dd__item"><a href="#Modules"> Modules &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp </a></div>

               <ul class="dd ul">
                   <li><div class="dd__item"> <a href="#A1">Algebra</a></div>
                       <ul><li><a href="#A4">Level 4 (about Year 10)</a>
                           <li><a href="#A5">Level&nbsp5&nbsp(about&nbspYear&nbsp10)</a>
                           <li><a href="#A6">Level 6 (Years 11-12)</a></li></ul>
                       </li> 

                   <li><a href="#SMA">Arithmetic</a>
                       </li>
               </ul>
           </li>  
       </ul>
    </div>

</td></tr></tbody></table>


// function to close all dropdown menus
function closeAllDropdowns() {
    const allDropdowns = document.querySelectorAll(".dd ul");
    allDropdowns.forEach(function (dropdown) {
        dropdown.classList.remove("show");
    });
}


// close all dropdown menus when document is clicked
document.documentElement.addEventListener("click", closeAllDropdowns);


</body>
</html>  

我不擅长 JavaScript。里面的javascript是从网上借来的。这是我尝试过但没有成功的来自互联网的大约 20 个片段之一(包括来自 Stack Overflow 的几个片段)。我也尝试过自己编写并让 ChatGPT 来编写一些。而且我请了三位有一定javascript知识的朋友来看一下。一切都没有成功。我认为如果我能找到正确的代码,六行 JavaScript 就可以完成这项工作。

javascript html menu dropdown navbar
1个回答
0
投票

请查找更新的代码

// function to close all dropdown menus
function closeAllDropdowns() {    
    const allDropdowns = document.querySelectorAll(".dd ul");
    allDropdowns.forEach(function (dropdown) {
        // dropdown.classList.remove("show");
        dropdown.style.display = 'none';
    });
}

// function to open all dropdown menus
function openAllDropdowns() {    
    const allDropdowns = document.querySelectorAll(".dd ul");
    allDropdowns.forEach(function (dropdown) {        
        dropdown.style.display = '';
    });
}

// close/open all dropdown menus when document is clicked
document.documentElement.addEventListener("click", closeAllDropdowns);
document.documentElement.addEventListener("mouseover", openAllDropdowns);

祝你好运!!!

© www.soinside.com 2019 - 2024. All rights reserved.