2012-06-21 83 views
2

希望有更好的JavaScript知识的人可以协助,我想使用以下内容在我们的网站上创建展开/折叠div,但是这会自动加载为展开最初需要在崩溃时加载它。Javascript展开/折叠div加载展开而不是折叠

下面的代码:

<script type="text/javascript"> 
// toggle specific 
function toggleDiv(id1,id2) { 
    var tag = document.getElementById(id1).style; 
    var tagicon = document.getElementById(id2); 

    if(tag.display == "none") { 
    tag.display = "block"; 
    tagicon.innerHTML = "&nbsp;-&nbsp;"; 
    } else { 
    tag.display = "none"; 
    tagicon.innerHTML = "&nbsp;+&nbsp;"; 
    } 
} 

function expandAll(cnt) { 
    for(var x=1; x<=cnt; x++) { 
    document.getElementById('content'+x).style.display="block"; 
    document.getElementById('icon'+x).innerHTML="&nbsp;-&nbsp;"; 
    } 
} 

function collapseAll(cnt) { 
    for(var x=1; x<=cnt; x++) { 
    document.getElementById('content'+x).style.display="none"; 
    document.getElementById('icon'+x).innerHTML="&nbsp;+&nbsp;"; 
    } 
} 

</script> 

<style type="text/css"> 
.title { 
    padding:5px; 
    border:1px solid #CCCCCC; 
    font:15px arial; 
    width:300px; 
    cursor:pointer; 
    height:20px; 
} 

.item { 
    padding:5px; 
    border:1px solid #CCCCCC; 
    font:12px verdana; 
    width:300px; 
} 

.item div { 
    border-bottom:1px dashed #CCCCCC; 
    padding:5px; 
} 

.button { 
    border:1px solid #CCCCCC; 
    padding:5px; 
    cursor:pointer; 
} 

</style> 

</head> 
<body> 

</div> 
<div class="title" onClick="javascript:toggleDiv('content1','icon1');"> 
    <span style="float:left">Sample Title 1</span> 
    <span id="icon1" style="float:right">&nbsp;-&nbsp;</span> 
</div> 
<div id="content1" class="item"> 
    <div>Item 1</div> 
    <div>Item 2</div> 
    <div>Item 3</div> 
</div> 
<div class="title" onClick="javascript:toggleDiv('content2','icon2');"> 
    <span style="float:left">Sample Title 2</span> 
    <span id="icon2" style="float:right">&nbsp;-&nbsp;</span> 
</div> 
<div id="content2" class="item"> 
    <div>Item 1</div> 
    <div>Item 2</div> 
    <div>Item 3</div> 
</div> 

回答

2

有两种方法可以做到这一点。首先,你可以通过用+来代替-s并使用合适的css风格,来启动所有的html。或者,建议您可以将collapseAll绑定到onload上 - 我建议您查看一下围绕window.onload的最佳实践,以获得最佳做法Best practice for using window.onload,因为如果您不小心,可能会遇到令人讨厌的行为

+0

您好,感谢您的回复。你可能会帮助我在哪里放置window.onload代码?当涉及到JavaScript时,并不是真的那么简单,基本上是寻找最简单的方法来根据需要来实现这一点。谢谢 – user994319

+0

当然。链接的问题实际上建议在窗口onload事件上使用事件侦听器,而不是直接设置函数,但如果您想直接设置它,我建议您在当前的脚本标记中进行此操作,就在您定义collapseAll的位置 – brettcvz

1
<div class="title" onclick="javascript:toggleDiv('content1','icon1');"> 
        ^should be lowercase 
    <span style="float:left">Sample Title 1</span> 
    <span id="icon1" style="float:right">&nbsp;+&nbsp;</span> 
              ^should expand 
</div> 
<div id="content1" class="item" style="display:none;"> 
           ^should be hidden^
    <div>Item 1</div> 
    <div>Item 2</div> 
    <div>Item 3</div> 
</div> 

但是注意,非JS用户不会看到什么呢。