使用JavaScript一次只显示一个div

时间:2012-11-26 00:49:06

标签: javascript html css

我只是在玩一些JavaScript,我是新手,所以这可能是一个简单的解决方案。基本上我想要的是一次只能显示1 div,所以如果用户点击一个链接来展示div,那么曝光的当前div将会崩溃点击一下就会出现。

我已经包含以下代码:

<html> 
    <head>

        <title> test</title>
        <LINK href="blah.css" rel="stylesheet" type="text/css">
        <script language="javascript" type="text/javascript">
        function toggle2(showHideDiv, switchTextDiv) {
    var ele = document.getElementById(showHideDiv);
    var text = document.getElementById(switchTextDiv);
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "restore";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "collapse";
    }
}
    function toggle22(showHideDiv2, switchTextDiv2) {
    var ele = document.getElementById(showHideDiv2);
    var text = document.getElementById(switchTextDiv2);
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "restore";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "collapse";
    }
}


        </script>
    </head>
    <body>
        <div id="mainContent">    
<div id="headerDiv">
     <div id="titleText">Change Password - Click here ==></div><a id="myHeader" href="javascript:toggle2('myContent','myHeader');" >restore</a>
</div>

<div style="clear:both;"></div>

<div id="contentDiv">
     <div id="myContent" style="display: none;">This is the content that is dynamically being collapsed.</div>

<!--DIV2 -->

<div id="headerDiv2">
     <div id="titleText2">Change Username - Click here ==></div><a id="myHeader2" href="javascript:toggle22('myContent2','myHeader2');" >restore</a>
</div>

<div style="clear:both;"></div>

<div id="contentDiv2">
     <div id="myContent2" style="display: none;">This is the content that is dynamically being collapsed.</div>




</div>
        </div>
    </body>
</html>

CSS:

#headerDiv, #contentDiv {
float: left;
width: 510px;
}
#titleText {
float: left;
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#myHeader {
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#headerDiv {
background-color: #0037DB;
color: #9EB6FF;
}
#contentDiv {
background-color: #FFE694;
}
#myContent {
margin: 5px 10px;
}
#headerDiv a {
color: gold;
float: right;
margin: 10px 10px 5px 5px;
}
#headerDiv a:hover {
color: #FFFFFF;
}




#headerDiv2, #contentDiv2 {
float: left;
width: 510px;
}
#titleText2 {
float: left;
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#myHeader2 {
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#headerDiv2 {
background-color: #0037DB;
color: #9EB6FF;
}
#contentDiv2 {
background-color: #FFE694;
}
#myContent2 {
margin: 5px 10px;
}
#headerDiv2 a {
color: gold;
float: right;
margin: 10px 10px 5px 5px;
}
#headerDiv2 a:hover {
color: #FFFFFF;
}

1 个答案:

答案 0 :(得分:0)

style.display仅反映在元素上明确设置的样式。除非您在HTML中使用style="display:block"指定它,否则style.display的初始值将为空,即使CSS级联应用的该属性的默认值确实为block