3 回答
TA贡献1827条经验 获得超8个赞
默认情况下,您可以简单地在单击 div 时隐藏该berlindiv zurich,对于单击其他 div 也可以执行相同的操作,例如:
function male() {
var x = document.getElementById("berlin");
document.getElementById("zurich").style.display = "none";
x.style.display = x.style.display === "none" ? "block" : "none";
}
function female() {
var x = document.getElementById("zurich");
document.getElementById("berlin").style.display = "none";
x.style.display = x.style.display === "none" ? "block" : "none";
}
div {
background-color: #EEE;
border: 2px solid green;
padding: 20px;
margin: 20px;
}
<div class="toggle">
<button onclick="male()">open 1</button>
<button onclick="female()">open 2</button>
</div>
<div id="berlin" style="display: none">
Toggle 1 content
</div>
<div id="zurich" style="display: none">
Toggle 2 content
</div>
TA贡献1828条经验 获得超6个赞
您还可以使用该hidden属性,例如:
let x = document.getElementById("berlin");
let y = document.getElementById("zurich");
function male() {
x.hidden = !x.hidden;
y.hidden = true;
}
function female() {
y.hidden = !y.hidden;
x.hidden = true;
}
<div class="toggle">
<button onclick="male()">open 1</button>
<button onclick="female()">open 2</button>
</div>
<div id="berlin" hidden>
Toggle 1 content
</div>
<div id="zurich" hidden>
Toggle 2 content
</div>
TA贡献1815条经验 获得超6个赞
如果您有更多切换按钮和更多要显示隐藏的容器,那么这应该会有所帮助
const toggleContainers = document.querySelectorAll('.toggle-container');
function hideAllToggles() {
toggleContainers.forEach(toggle => {
toggle.classList.add('hidden');
});
}
hideAllToggles();
function showToggle(id) {
hideAllToggles();
var x = document.querySelector(`#${id}`);
x.classList.remove('hidden');
x.classList.remove('active');
}
.hidden {
display: none;
}
.active {
display: block;
}
<div class="toggle">
<button onclick="showToggle('berlin')">open 1</button>
<button onclick="showToggle('zurich')">open 2</button>
</div>
<div class="toggle-container" id="berlin">
Toggle 1 content
</div>
<div class="toggle-container" id="zurich">
Toggle 2 content
</div>
- 3 回答
- 0 关注
- 114 浏览
添加回答
举报