gpt4 book ai didi

javascript - JS 切换可见性 : How to Hide Already Visible Elements on Click

转载 作者:行者123 更新时间:2023-11-28 05:37:11 25 4
gpt4 key购买 nike

当我单击链接时,我使用 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>

最佳答案

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

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>

关于javascript - JS 切换可见性 : How to Hide Already Visible Elements on Click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39260001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com