javascript - 按钮切换显示显示隐藏

标签 javascript html css

我想通过单击按钮显示隐藏这些层的显示。我不知道如何使用 2 个按钮和 2 个 div...

HTML:

<div id="first">This is the FIRST div</div>
<div id="second">This is the SECOND div</div>
<button id="toggle">Show first div and hide second div</button>
<button id="toggletoo">Show second div and hide first div</button>

CSS:

#first {
  display: none;
}
#second {
  display: none;
}

Js:

const targetDiv = document.getElementById("first");
const btn = document.getElementById("toggle");
btn.onclick = function () {
  if (targetDiv.style.display !== "none") {
    targetDiv.style.display = "block";
  } else {
    targetDiv.style.display = "none";
  }
}

https://codepen.io/MaaikeNij/pen/YzrgbQw

最佳答案

试试下面的代码:

#first{
  display: block; /* <--- change */
}
#second {
  display: none;
}
const firstDiv = document.getElementById("first");
const secondDiv = document.getElementById("second");
document.getElementById("toggle").onclick = function () {
  if (firstDiv.style.display === "none") {
    firstDiv.style.display = "block";
    secondDiv.style.display = "none";
  } else {
    firstDiv.style.display = "none";
    secondDiv.style.display = "block";
  }
}

关于javascript - 按钮切换显示显示隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70752348/

相关文章:

javascript - 通过 SSL 的 Skype CDN

javascript - Visual Studio 代码调试器从源映射中的内联内容提供文件

javascript - jquery remove 只影响第一个跨度

javascript - 在 javascript 中创建了 SVG,但它不会连接到 CSS 或显示在浏览器中。任何解决方案?

javascript - 在模板 Web 组件中实现框架

javascript - 我如何确定何时溢出 :hidden parent is overflown 的 child

javascript - 在元素符号上为图像 slider jquery添加功能

asp.net - 超链接的字体大小问题

javascript - 如何让文本区域的光标在拖放时移动到突出显示文本的末尾?

javascript - 在 AngularJS 中选择下拉项时显示概述文本