【问题标题】:Why isn't the display toggling in Javascript? [duplicate]为什么在 Javascript 中显示不切换? [复制]
【发布时间】:2021-12-16 09:36:57
【问题描述】:

我正在尝试做一些事情,点击一个 div 会在块和无之间切换另一个 div 的显示。

<div id="filtertop" onclick="toggleFilter()">Filter</div>
 function toggleFilter() {
      let x = document.getElementById("filter").style.display;
      if (x == "none") {
        x = "flex";
      }
      else{
        x = "none";
      }
        
    }

目前,当我单击 id="filtertop"; 的 div 时,代码什么也不做。显示应该变为无。

【问题讨论】:

  • 不,x 正在更改为 "none"(然后,x 没有任何其他操作)。您永远不会将任何内容分配回document.getElementById('filter').style.display

标签: javascript html css flexbox


【解决方案1】:

你是这个意思?

function toggleFilter() {
  let x = document.getElementById("filter");
  if (x.style.display == "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }

}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div id="filter">div with ID</div>

【讨论】:

  • .style 不需要重复; const x = document.getElementById("filter").style;也可以。切换类仍然更好。 onclick 仍然是不好的做法。
  • 谢谢你教给我的要点
【解决方案2】:

@CherryDT 在 cmets 中已经解释了您的代码问题。

要么你必须将你的 JS 更改为:

function toggleFilter() {
  let x = document.getElementById("filter");
  if (x == "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}

更智能、更现代的解决方案是使用classList.toggle('class-name'),如下例所示。这应用了一个 CSS 类和切换。因此,您不需要使用 if / else 语句。

function toggleFilter() {
  document.querySelector('.filter').classList.toggle('d-none');
}
.filter {
  display: flex;
}

.d-none {
  display: none;
}


/* for styling purpose only */
.filter {
  height: 50vh;
  background-color: red;
  grow: 1;
  margin-top: 20px;
}

#filtertop {
  font-size: 2em;
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>

<div class="filter">Filter Element</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多