Как я могу скрыть div по умолчанию? - PullRequest
0 голосов
/ 06 августа 2020

В настоящее время содержимое сценария ниже отображается по умолчанию. Как я могу настроить код, чтобы он был скрыт по умолчанию, и чтобы скрыть или показать его, необходимо нажать кнопку.

<script>
function myFunction_1() {
  var x = document.getElementById("myDIV");
  var y = document.getElementById("myDIV2");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function myFunction_2() {
  var y = document.getElementById("myDIV2");
  if (y.style.display === "none") {
    y.style.display = "block";
  } else {
    y.style.display = "none";
  }
}
<script>

#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV">
  This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2">
  This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

1 Ответ

3 голосов
/ 06 августа 2020

Просто установите display: none как встроенный стиль для каждого элемента.

<div id="myDIV" style="display: none;">
  This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2" style="display: none;">
  This is my DIV element.
</div>

Живой пример:

function myFunction_1() {
  var x = document.getElementById("myDIV");
  var y = document.getElementById("myDIV2");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function myFunction_2() {
  var y = document.getElementById("myDIV2");
  if (y.style.display === "none") {
    y.style.display = "block";
  } else {
    y.style.display = "none";
  }
}
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV" style="display: none;">
  This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2" style="display: none;">
  This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...