显示其他 div 时隐藏 div

我正在构建一个带有 3 个按钮的页面,每个按钮打开一个不同的 div 元素。我想要的是当时只显示一个 div。所以当一个 div 打开时,另一个 div 应该关闭。


我设法创建按钮,每个按钮打开一个不同的 div 元素。但是我想不出在打开其他 div 时自动关闭 div 的方法。


var button1 = document.getElementById("button1");

var button2 = document.getElementById("button2");

var button3 = document.getElementById("button3");

var content1 = document.getElementById("content1");

var content2 = document.getElementById("content2");

var content3 = document.getElementById("content3");

content1.style.display = "none";

content2.style.display = "none";

content3.style.display = "none";

button1.addEventListener("click", showContent1);

button2.addEventListener("click", showContent2);

button3.addEventListener("click", showContent3);


function showContent1() {

  if (content1.style.display !== "none") {

    content1.style.display = "none"

  } else {

    content1.style.display = "block";

  }

}


function showContent2() {

  if (content2.style.display !== "none") {

    content2.style.display = "none"

  } else {

    content2.style.display = "block";

  }

}


function showContent3() {

  if (content3.style.display !== "none") {

    content3.style.display = "none"

  } else {

    content3.style.display = "block";

  }

}

#button1,

#button2,

#button3 {

  width: 50px;

  height: 50px;

  background: lightblue;

  margin: 5px;

  cursor: pointer;

}


#content1,

#content2,

#content3 {

  width: 100px;

  height: 50px;

  background: blue;

  color: white;

  margin: 5px;

}

<div id="button1">button 1</div>

<div id="button2">button 2</div>

<div id="button3">button 3</div>

<div id="content1">content 1</div>

<div id="content2">content 2</div>

<div id="content3">content 3</div>


尚方宝剑之说
浏览 185回答 3
3回答

慕标5832272

你甚至可以创建一个标签系统,无需任何JavaScript在所有使用单选按钮的CSS技巧。如果选中了单选按钮,则使用同级选择器:显示下一个 div ~。input{&nbsp; display: none;}label{&nbsp; display: inline-block;&nbsp; padding: 3px;&nbsp; border: 1px solid #aaa;}label:hover{&nbsp; cursor: pointer;}.display{&nbsp; display: none;}[type=radio]:checked ~ .display{&nbsp; display: block;}<section>&nbsp; <label for="div1">Show div 1</label>&nbsp; <label for="div2">Show div 2</label>&nbsp; <label for="div3">Show div 3</label></section><section>&nbsp; <input type="radio" id="div1" name="tab-nav" checked />&nbsp; <div class="display">&nbsp; &nbsp; Text from div 1.&nbsp; </div></section><section>&nbsp; <input type="radio" id="div2" name="tab-nav" />&nbsp; <div class="display">&nbsp; &nbsp; Text from div 2. It's cool.&nbsp; </div></section><section>&nbsp; <input type="radio" id="div3" name="tab-nav" />&nbsp; <div class="display">&nbsp; &nbsp; Text from div 3. Definitely a cool css trick.&nbsp; </div></section>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript