我正在构建一个带有 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>
慕标5832272
相关分类