当我点击链接时,我正在使用Javascript来显示/隐藏页面上的元素。它按预期工作。但是,当我点击链接时,我希望隐藏所有其他可见元素。我怎样才能做到这一点?提前谢谢!
这是我的代码:
**JS**
<script type="text/javascript" async>
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
**CSS/HTML**
div {
display:none;
}
<a href="#" onclick="toggle_visibility('punctuation');">PUNCTUATION</a>
<a href="#" onclick="toggle_visibility('grammar');">GRAMMAR</a>
<div id="punctuation">
Punctuation stuff
</div>
<div id="grammar">
Grammar stuff
</div>
答案 0 :(得分:0)
首先将所有元素设置为您正在切换的项目的显示。然后将你正在切换的元素设置为相反的。
function toggle_visibility(id) {
var e = document.getElementById(id);
var curDisplay = e.style.display;
el = document.getElementsByClassName('foo');
el.forEach(function(e){
// this can be set as 'none' is you want hide instead of toggle
e.style.display = curDisplay;
})
if (curDisplay == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div class="foo" id="punctuation">
Punctuation stuff
</div>
<div class="foo" id="grammar">
Grammar stuff
</div>