如何在Javascript中隐藏元素

3

我希望在一开始时隐藏文本,点击按钮后才能显示。如果有人能找出我的代码中的错误,我将非常感激。

function F1()
{
  var x = document.getElementById("step1DIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<!DOCTYPE html>
<html>

<body>

  <button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV">
    <p> text </p>
  </div>

</body>

</html>


在设置之前,style.display 是不可用的。我建议在 CSS 中使用 .hide{ display:none; },然后使用 Element.classList.add('hide')Element.classList.remove('hide')Element.classList.toggle('hide')。除非你想要大量输入,否则我通常建议使用 CSS 类来进行样式设置。 - StackSlave
4个回答

2

您需要在HTML中给它一个初始样式来隐藏它。

function F1()
{
  var x = document.getElementById("step1DIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
  <button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV" style="display: none;">
    <p> text </p>
  </div>

但是内联样式是不良设计,最好使用CSS类。

function F1()
{
  var x = document.getElementById("step1DIV");
  x.classList.toggle("hidden");
}
.hidden {
  display: none;
}
<button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV" class="hidden">
    <p> text </p>
  </div>


更好的做法是利用HTML标准属性hidden - Ronnie Royston
@RonnieRoyston 通常情况下,类和CSS更可取,因为您可以轻松地在一个地方更改演示方式。 - Barmar
具体来说,关于隐藏元素:hidden属性 - Ronnie Royston

0

我刚开始将其定义为“none”,如下:

<div id="step1DIV" style="display: none"> 

0

尝试最初将step1 DIV的display设置为none,可以使用内联样式或CSS。

您还可以尝试在页面加载时运行函数。


0

您想要切换在HTML标准中定义的hidden属性(链接)

function F1 () {
  document.getElementById("a").toggleAttribute("hidden");
}
<!DOCTYPE html>
<html>

<body>

  <button onclick="F1()"> <b>Step 1</b> </button>
  <div id=a>
    <p> text </p>
  </div>

</body>

</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接