[英]JS Toggle Visibility: How to Hide Already Visible Elements on Click
I'm using Javascript to show / hide elements on a page when I click the links. 当我点击链接时,我正在使用Javascript来显示/隐藏页面上的元素。 It works as expected.
它按预期工作。 However, when I click on the links, I want all other visible elements to be hidden.
但是,当我点击链接时,我希望隐藏所有其他可见元素。 How can I achieve this?
我怎样才能做到这一点? Thank you in advance!
先感谢您!
Here's my code: 这是我的代码:
**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>
First set all elements to the display of the item u are toggling. 首先将所有元素设置为您正在切换的项目的显示。 and then set the element you are toggling to the opposite.
然后将要切换的元素设置为相反的元素。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.