使用javascript切换div的可见性 [英] Toggling visibility of divs using javascript
问题描述
我有以下代码,用于启用div在可见和隐藏之间切换:
I have the following code, for enabling a div from toggling between visible and hidden:
function toggle_visibility(id,$this) {
var e = document.getElementById(id);
if(e.style.display == 'block')
{
e.style.display = 'none';
}
else
{
e.style.display = 'block';
}
}
基本上当我单击一个链接onclick = toggle_visibility('4s');在其中显示指定的div,然后当您再次单击它被隐藏。
Basically when I click a link that has onclick="toggle_visibility('4s'); within it then the specified div is shown and then when you click again it is hidden.
我的问题是当相同的代码使用多个链接,并且您切换一个的可见性,然后另一个,前一个仍然显示。我将如何去只是启用一个div显示时切换,然后如果另一个切换另一个隐藏?
My problem is when the same code is use for multiple links, and you toggle the visibility of one and then the other, the previous one is still shown. How would I go about only enabling one div to be shown when toggled and then if another is toggled the other is hidden?
推荐答案
这里是使用jquery的通用示例。
Here is a generic example using jquery.
标记
<section>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
</section>
<a href="#1">one</a>
<a href="#2">two</a>
<a href="#3">three</a>
<a href="#4">four</a>
JS
var divs = $('section div'),
links = $('a');
links.click(function(){
$(this.hash).toggle().siblings().hide();
return false;
});
这篇关于使用javascript切换div的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!