HTML按钮,单击按钮时进行切换,并切换所有其他按钮(折叠信息)

我是HTML-CSS的新手。我创建了一些按钮,可以单击它们,它们将显示更多信息。但是我也希望当单击一个按钮时,所有其他按钮“折叠”它们所显示的信息。我尝试查找它并使用代码,但没有设法做到这一点。希望能有所帮助!

function thirdP() {
  var x = document.getElementById("Project3");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
 function secondP() {
  var x = document.getElementById("Project2");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
function firstP() {
  var x = document.getElementById("Project1");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<ul>
     <button class="button" onclick="firstP">1st Project</button>
     <div id="Project1" style="display:none" align="right">Information about the first project...</div>
</ul>
<ul>
     <button class="button" onclick="secondP">2nd Project</button>
     <div id="Project2" style="display:none" align="right">Information about the second project...</div>
</ul>
<ul>
     <button class="button" onclick="thirdP">2nd Project</button>
     <div id="Project3" style="display:none" align="right">Information about the second project...</div>

我知道这可能效率很低,因为我为每个按钮编写了相同的Javascript函数。我还无法创建一个适用于所有ID的函数。

马门

在点击通过所有的元素按钮简单循环id开始与Project以一套display = "none"使用Document.querySelectorAll()Array.prototype.forEach()然后仅显示nextElementSibling单击按钮的。请尝试以下操作:

function project(btn) {
  document.querySelectorAll('[id^="Project"]').forEach(div => div.style.display = "none");
  btn.nextElementSibling.style.display = "block";
}
<ul>
  <button class="button" onclick="project(this)">1st Project</button>
  <div id="Project1" style="display: none;" align="right">Information about the first project...</div>

</ul>

<ul>
  <button class="button" onclick="project(this)">2nd Project</button>
  <div id="Project2" style="display: none;" align="right">Information about the second project...</div>
</ul>

<ul>
  <button class="button" onclick="project(this)">3rd Project</button>
  <div id="Project3" style="display: none;" align="right">Information about the third project...</div>
</ul>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章