JavaScript - 隐藏所有其他divs [英] JavaScript - Hide all other divs

查看:101
本文介绍了JavaScript - 隐藏所有其他divs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多只在点击链接后才可见的div。如何关闭所有打开的div,以便只有点击一个可见?

我使用这个.js:

I've a number of divs that are only visible after clicking a link. How to close all open divs so that only the clicked one is visible?
I'm using this .js:

    function showhide(id){
        if (document.getElementById) {
        var divid = document.getElementById(id);
        divid.style.display = (divid.style.display=='block'?'none':'block');
        } }

        <a href="javascript:void(null)" onclick="showhide('features');">features</a>
<a href="javascript:void(null)" onclick="showhide('design');">design</a>
<a href="javascript:void(null)" onclick="showhide('create');">create</a>

感谢
Uli

Thanks Uli

推荐答案

一种方法是添加一个类并寻找隐藏它们的元素(,如其他答案中所示)

One way is to add a class and seek the elements based on that to hide them (as shown in other answers)

另一种方法是将元素的状态存储在一个对象中,并使用它来标识需要关闭的元素。

An alternative is to store the state of the elements in an object and use that to identify the open ones that need closing..

var divState = {}; // we store the status in this object
function showhide(id) {
    if (document.getElementById) {
        var divid = document.getElementById(id);

        divState[id] = (divState[id]) ? false : true; // initialize / invert status (true is visible and false is closed)
        //close others
        for (var div in divState){
            if (divState[div] && div != id){ // ignore closed ones and the current
                document.getElementById(div).style.display = 'none'; // hide
                divState[div] = false; // reset status
            }
        }
        divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
    }
}

演示 http://jsfiddle.net/gaby/LfzYc/

这篇关于JavaScript - 隐藏所有其他divs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆