CSS+JS製作可摺疊內容塊

來源:互聯網
上載者:User
代碼解析

HTML 程式碼部分

<div class="save">

<h1><a href="javascript:void(0)" class="dsphead"
onclick="dsp(this)">
<span class="dspchar">+</span> heading</a></h1>
<div class="dspcont">section</div>
<!--以上部分是第一個heading,h1中有個onclick觸發了JS中的dsp(loc)函數,初始的+號是在class為dspcont的<span>裡的,初始隱藏的內容則是在class為dspcont的div裡的-->

<h1><a href="javascript:void(0)" class="dsphead"
onclick="dsp(this)">
<span class="dspchar">+</span> heading</a></h1>
<div class="dspcont">

<h2><a href="javascript:void(0)" class="dsphead"
onclick="dsp(this)">
<span class="dsphead">+</span> heading</a></h2>
<div class="dspcont">section</div>

<h2><a href="javascript:void(0)" class="dsphead"
onclick="dsp(this)">
<span class="dspchar">+</span> heading</a></h2>
<div class="dspcont">section</div>
</div>
</div>

CSS代碼部分

.save{
behavior:url(#default#savehistory);}
/*防止後退時清空該範圍內的text內容[這裡為什麼用到這個不是很明白...]*/

a.dsphead{
text-decoration:none;
margin-left:1.5em;}
/*對串連樣式的設定*/

a.dsphead:hover{
text-decoration:underline;}
/*串連hover的狀態*/

a.dsphead span.dspchar{
font-family:monospace;
font-weight:normal;}
/*設定head和符號的字型*/

.dspcont{
display:none;
margin-left:1.5em;}
/*設定內容部分初始樣式,display是none*/

JS代碼部分

<script type="text/javascript"><!--
function dsp(loc){
if(document.getElementById){
foc=loc.firstChild.innerHTML?
loc.firstChild:
loc.firstChild.nextSibling;/*使foc為當前點的下一個子項目的innerHTML也就是那個帶+符號的<span>的innerHTML*/
foc.innerHTML=(foc.innerHTML=='+')?'-':'+';/*判斷<span>裡的內容是-還是+號,是+就變-,是-就變+*/
foc=loc.parentNode.nextSibling.style?
loc.parentNode.nextSibling:
loc.parentNode.nextSibling.nextSibling;/*將判斷位置移動到<a>的父兄(就是h1後面的隱藏div)*/
foc.style.display=foc.style.display=='block'?'none':'block';}/*判斷div的display是none還是block,設定為相反的值*/}

if(!document.getElementById)
document.write('<style type="text/css"><!--\n'+
'.dspcont{display:block;}\n'+
'//--></style>');
//--></script>/*針對不支援DOM的瀏覽器,將隱藏內容全部顯示*/

<noscript>
<style type="text/css"><!--
.dspcont{display:block;}
//--></style>/*針對不支援js的瀏覽器,將隱藏內容顯示*/
</noscript>

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.