0

我正在尝试使用 Html 和 Javascript 创建一个下拉列表,但由于某种原因它无法正常工作,尽管观看了 Youtube 上的每个视频。这是我正在使用的代码:HTML:

<div class="dropdown">
    <button id="dropdownbtn" onclick="dropdown()">Courses &#9662</button>
    <div id="dropdown-items">
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
    </div>
</div>

JavaScript:

var flag = 0;
function dropdown() {

    if (flag==0) {
        document.getElementById("dropdown-items").style.display = "none";
        flag=1;
    } 

    if (flag==1) {
        document.getElementById("dropdown-items").style.display = "block";
        flag=0;
    }
}

css也将显示设置为无。谢谢您的帮助。

4

3 回答 3

1

它实际上正在工作,但是您必须放置 else if 因为在 if 条件下您将标志更改为 1 并且第二个条件变为 true

var flag = 0;

function dropdown() {

    if (flag==0) {

        document.getElementById("dropdown-items").style.display = "none";

        flag=1;
    } 
    else if (flag==1) {

        document.getElementById("dropdown-items").style.display = "block";

        flag=0;
    }
}
于 2019-09-14T08:37:50.620 回答
1

一个更简单的解决方案,使用三元运算符:

document.getElementById("dropdown-items").style.display = flag === 0 ? 'none' : ' block'
于 2019-09-14T08:46:14.633 回答
1

为什么不在这里使用toggleclass?

    <div class="dropdown">
    <button id="dropdownbtn" onclick="dropdown()">Courses &#9662</button>
    <div id="dropdown-items">
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
    </div>
    </div>

添加类似的css

#dropdown-items {
 display: none;
}

.toggleShow {
  display: block;
}

在你的脚本中

<script>
function dropdown() {
   var element = document.getElementById("dropdown-items");
   element.classList.toggle("toggleShow");
}
</script>
于 2019-09-14T08:46:41.020 回答