下面的代码正确地切换了各个div,但是,当我切换时,它在彼此下方显示了启用的div,但是我需要“ 一次只显示一个”。有想法吗?
NaN
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
谢谢
答案 0 :(得分:4)
在可见所选元素之前,您应该隐藏其他元素。
function toggle_visibility(id) {
const target = document.getElementById(id);
if (!target) return;
// Hide all other div elements.
const divs = document.querySelectorAll('.div');
for (const div of divs) {
div.style.display = 'none';
}
// Show selected one
target.style.display = 'block';
}
div {
width: 20px;
height: 20px;
}
#source {
background: red;
}
#share {
background: blue;
}
#report {
background: green;
}
<ul class="post-advanced-menu">
<li><a href="#" onclick="toggle_visibility('source');">Source</a></li>
<li><a href="#" onclick="toggle_visibility('share');">Share</a></li>
<li><a href="#" onclick="toggle_visibility('report');">Report</a></li>
</ul>
<!-- Source -->
<div id="source" class="div" style="display: none;"></div>
<!-- Share -->
<div id="share" class="div" style="display: none;"></div>
<!-- Report -->
<div id="report" class="div" style="display: none;"></div>
答案 1 :(得分:0)
一种解决方案是在单击之前隐藏其他项目。
如果可见,它还会隐藏单击的div。
您可以为每个div添加一个类。例如:class="item"
,以便在此过程中提供帮助。
<ul class="post-advanced-menu">
<li><a href="#" onclick="toggle_visibility('source');">Source</a></li>
<li><a href="#" onclick="toggle_visibility('share');">Share</a></li>
<li><a href="#" onclick="toggle_visibility('report');">Report</a></li>
</ul>
<!-- Source -->
<div id="source" class="item" style="display: none;">1</div>
<!-- Share -->
<div id="share" class="item" style="display: none;">2</div>
<!-- Report -->
<div id="report" class="item" style="display: none;">3</div>
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block') {
e.style.display = 'none'
} else {
document.querySelectorAll('.item').forEach(function(div) {
div.style.display = 'none';
})
e.style.display = 'block';
}
}
答案 2 :(得分:0)
我建议使用类和数据属性的脚本不引人注目:
window.addEventListener("load",
() => document.querySelectorAll(".post-advanced-menu").forEach(
ele => ele.addEventListener("click",
e => {
var tgt = e.target;
var id = tgt.getAttribute("data-id");
document.querySelectorAll(".toggle").forEach(
ele => ele.style.display = ele.id == id ? "block" : "none")
})
)
)
.toggle {
display: none
}
<ul class="post-advanced-menu">
<li><a href="#" data-id="source">Source</a></li>
<li><a href="#" data-id="share">Share</a></li>
<li><a href="#" data-id="report">Report</a></li>
</ul>
<!-- Source -->
<div id="source" class="toggle">Source</div>
<!-- Share -->
<div id="share" class="toggle">Share</div>
<!-- Report -->
<div id="report" class="toggle">Report</div>