Как скрыть, а затем отобразить при нажатии нескольких элементов содержимого по умолчанию? - PullRequest
0 голосов
/ 06 августа 2020

У меня есть следующий код. По умолчанию он отображается, но я хочу скрыть его по умолчанию.

Кроме того, я не могу управлять обоими div, работает только 1 из переключателей отображения / скрытия, я хочу для них (но есть не удалось) оба работают.

Как я могу скрыть по умолчанию и развернуть при нажатии?

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

<br><br>

<button onclick="myFunction()">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>

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

</body>
</html>

Ответы [ 2 ]

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

Просто разделите функцию на первую кнопку и кнопку

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">
  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>
0 голосов
/ 06 августа 2020
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");

Вы перезаписываете переменную x. Назначьте myDIV2 другой переменной, например y, и повторите процесс.

Лучше просто назначить тот же class вместо id элементам, которые вы хотите скрыть, и просто переключить класс вместо того, чтобы пытаться получить каждый элемент по идентификатору.

https://ultimatecourses.com/blog/javascript-hasclass-addclass-removeclass-toggleclass

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...