简体   繁体   English

HTML/JavaScript 禁用元素

[英]HTML/JavaScript disable elements

I have a dropdown navigation on my site我的网站上有一个下拉导航

<ul>
    <li><a href="index.html">Homepage</a></li>
    <li><a href="#">Forum</a></li>
                
    <div class="dropdown">
        <button onclick="mainDropdown()" class="mainDropdown">Videos</button>
        <ul class="dropdownList" id="dropdownList">

            <button id="intro">Introduction</button>
            <button id="start">Getting Started</button>

        </ul>
    </div>
                    
    <li class="test"><a href="index.html">Contact</a></li>
</ul>

I have this in my html the UL around everything can be ignored as that isn't a part of the problem nor are the top two LIs我在我的 html 中有这个,所有东西的 UL 都可以忽略,因为这不是问题的一部分,前两个 LI 也不是

The problem I'm having is with the dropdown division.我遇到的问题是下拉部门。

function mainDropdown() {
    var dropdown = document.getElementById("dropdownList");
    dropdown.classList.toggle("active");
    if(dropdown.classList.contains("active")) {
        document.getElementById("intro").style.display = "block";
        document.getElementById("start").style.display = "block";
    } else if(!dropdown.classList.contains("active")) {
        setTimeout(() => {
            document.getElementById("intro").style.display = "none";
            document.getElementById("start").style.display = "none";
        }, 300);
    }
}

This is the javascript method (vanilla, trying to not use JQuery in this project, just as a heads up).这是 javascript 方法(香草,试图在这个项目中不使用 JQuery,只是作为提醒)。 This works fine - however, I'm looking for a better way to do this.这很好用 - 但是,我正在寻找一种更好的方法来做到这一点。 because when I come to add more sections then the javascript method is going to get quite lengthy.因为当我开始添加更多部分时,javascript 方法将会变得相当冗长。

Is there a method I can use to get the children of the dropdownList UL so I can loop through them and set their display?有没有一种方法可以用来获取 dropdownList UL 的子项,以便我可以遍历它们并设置它们的显示? Instead of adding a bunch of the same line.而不是添加一堆相同的行。

Is there a method I can use to get the children of the dropdownList UL so I can loop through them and set their display?有没有一种方法可以用来获取 dropdownList UL 的子项,以便我可以遍历它们并设置它们的显示?

You could get the list of items via querySelectorAll('#dropdownList > *') .您可以通过querySelectorAll('#dropdownList > *')获取项目列表。

Or you could use a css selector to toggle the display:或者您可以使用 css 选择器来切换显示:

#dropdownList {
  display: none;
}

#dropdownList.active {
  display: block;
}

Or if you need to do individual items for some reason:或者,如果您出于某种原因需要执行个别项目:

#dropdownList > * {
  display: none;
}

#dropdownList.active > * {
  display: block;
}

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

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