Javascript JS切换可见性:如何在单击时隐藏已可见的元素

Javascript JS切换可见性:如何在单击时隐藏已可见的元素,javascript,toggle,Javascript,Toggle,当我单击链接时,我正在使用Javascript显示/隐藏页面上的元素。它按预期工作。但是,当我单击链接时,我希望隐藏所有其他可见元素。我怎样才能做到这一点?提前谢谢你 这是我的密码: **JS** <script type="text/javascript" async> <!-- function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display ==

当我单击链接时,我正在使用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>
**JS**
**CSS/HTML**
div{
显示:无;
}
标点符号
语法材料

首先将所有元素设置为显示u正在切换的项目。然后将要切换的元素设置为相反的

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>
功能切换\u可见性(id){
var e=document.getElementById(id);
var curDisplay=e.style.display;
el=document.getElementsByClassName('foo');
el.forEach(功能(e){
//如果要隐藏而不是切换,可以将其设置为“无”
e、 style.display=curDisplay;
}) 
如果(curDisplay=='block')
e、 style.display='none';
其他的
e、 style.display='block';
}
标点符号
语法材料

首先将所有元素设置为显示u正在切换的项目。然后将要切换的元素设置为相反的

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>
功能切换\u可见性(id){
var e=document.getElementById(id);
var curDisplay=e.style.display;
el=document.getElementsByClassName('foo');
el.forEach(功能(e){
//如果要隐藏而不是切换,可以将其设置为“无”
e、 style.display=curDisplay;
}) 
如果(curDisplay=='block')
e、 style.display='none';
其他的
e、 style.display='block';
}
标点符号
语法材料

循环遍历body中的所有元素,如果它们不已经存在,则隐藏它们。您可能希望使用类名而不是样式属性。这将允许您使用
classList.toggle
方法。循环遍历body中的所有元素,如果它们不完整,则隐藏它们。您可能希望使用类名而不是样式属性。这将允许您使用
classList.toggle
方法。