javascript - 如何使 <div> 消失然后重新出现 onclick

标签 javascript html css

我正在尝试为我的网站制作一个常见问题解答部分,但我似乎无法让这个简单的代码工作,我已经被踩了几个小时,我试图让一个框消失 onclick ,然后重新出现。我已经让它消失了,但是当我添加重新出现时,整个事情就崩溃了。这是我的代码:

function showDiv() {
  document.getElementById('FAQPage').style.display = "block";
}

function closeDiv() {
  document.getElementById('FAQPage').style.display = "none";
}

function showOrHide() {
  if (document.getElementById('FAQPage').style.display = "block") {
    closeDiv()
  } else {
    showDiv()
  }
}
#FAQPage {
  background-color: #F8F8F8;
  width: 50%;
  position: absolute;
  left: 41%;
  height: auto;
  top: 10%;
  display: none;
}
<div id="FAQSidebar-buttons" onclick="showOrHide()">
  <h2 align="center">What kind of websites can we do?</h2>
</div>

<div id="FAQPage">
  <h1 align="center">What kind of websites can we do?</h1>
  <hr />
  <p align="center">Here at The Castle, when it comes to web design we can do almost anything! We can do Ecommerce, mobile websites, personal websites, and much more! Here, no matter what kind of business you have, you can get a site for it.</p>
</div>

最佳答案

您需要在您的条件中修复 =,使用 === 代替,第一个将赋值,第二个将检查。

并且不是每次都使用document.getElementById,而是使用一个变量来存储它,以防止每次都查询DOM

var faqPage = document.getElementById('FAQPage');

function showDiv() {
  faqPage.style.display = "block";
}

function closeDiv() {
  faqPage.style.display = "none";
}

function showOrHide() {
  if (faqPage.style.display === "block") {
    closeDiv()
  } else {
    showDiv()
  }
}
#FAQPage {
  background-color: #F8F8F8;
  width: 50%;
  position: absolute;
  left: 41%;
  height: auto;
  top: 10%;
  display: none;
}
<div id="FAQSidebar-buttons" onclick="showOrHide()">
  <h2 align="center">What kind of websites can we do?</h2>
</div>

<div id="FAQPage">
  <h1 align="center">What kind of websites can we do?</h1>
  <hr />
  <p align="center">Here at The Castle, when it comes to web design we can do almost anything! We can do Ecommerce, mobile websites, personal websites, and much more! Here, no matter what kind of business you have, you can get a site for it.</p>
</div>

关于javascript - 如何使 <div> 消失然后重新出现 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41730653/

相关文章:

javascript - 如何在 hadoop map reduce 编程框架中打印中间数据

javascript - 原型(prototype)链中的函数解析如何将 Object.prototype 作为构造函数

css - 提取主题感知样式的 CSS 差异

css - 将 sass 变量应用于父元素的所有元素

javascript - 如何在 react-CKEditor 组件中固定图像的宽度和高度?

css - 附加到 SCSS @mixin 的奇怪字符

javascript - 通过 javascript 在所有浏览器中以 % 形式返回 CSS 属性的准确值

javascript - 使用 document.querySelector()

html - 什么是伪元素?

javascript - 无法将值传递回 HTML 页面