简体   繁体   English

如何修复代码以获取使下拉菜单正常工作的功能?

[英]How can I fix my code to get the functions to make the dropdown menu work?

I am creating a clickable dropdown menu for my website and I can't seem to get the "dropdown" part of the code to work. 我正在为我的网站创建一个可单击的下拉菜单,但似乎无法使代码的“下拉”部分正常工作。 The functions are intact when using console.log to test. 使用console.log进行测试时,这些功能是完整的。

I am not quite sure where in my code I am missing something in order for the functions to do what they should be doing, which is to have the menu dropdown. 我不太确定我的代码中缺少什么,以便功能可以执行其应做的事情,即具有菜单下拉菜单。 The links just appear below the dropdown button. 链接仅出现在下拉按钮下方。 I provide my code below. 我在下面提供我的代码。 I also have a css stylesheet. 我也有一个CSS样式表。

  <header class="topheader">
      <div id="dropdown">
        <button onclick="myFunction()"id="dropbtn">Menu</button>
        <div id="myDropdown" id="dropdown-content">
          <a href="About Me.html">About Me</a>
          <a href="Featured Works.html">Featured Works</a>
        </div>
      </div>
      <script>

      function myFunction() {
        console.log("test");
       document.getElementById("myDropdown").classList.toggle("show-content");`
      }

      window.onclick = function(event){

        console.log("test");
        if (!event.target.matches('dropbtn')) {
          var dropdowns =
        document.getElementsByClassName("dropdown-content");
            var i;
            for (i = 0; i <
          dropdowns.length; i++) {
              var openDropdown =
          dropdowns[i];
              if (openDropdown.classList.contains("show-content")) {
                openDropdown.classList.remove("show-content")

              }
          }

        }
      }
    </script>
    </header>

Check the id of the myDropdown div. 检查myDropdown div的ID。

You are querying for document.getElementsByClassName("dropdown-content"); 您正在查询document.getElementsByClassName("dropdown-content");

But according to your div you set the ID twice I guess you meant to set the class to dropdown-content 但是根据您的div,您两次设置了ID,我想您是想将类设置为dropdown-content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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