2013-09-25 184 views
0

我正在學習JavaScript,我試圖切換一個簡單的隱藏和揭示效果沒有運氣。目前效果只能通過點擊具有相同參考的另一個div來取消。Javascript切換隱藏

這裏是我的javascript:

var $ = jQuery; 

$(document).ready(function(){ 
    $('.section').hide(); 
}); 

function showMe(num){ 
    $('.section').hide(0); 
    $('#div_one'+num).fadeIn(1000); 

} 

這裏是我的CSS:

.height-auto 

{ 
    height:auto; 
} 
.section 

{ 
    width:552px; 
    min-height:300px; 

} 

這裏是我的HTML:

<div class="section home-things visible" id="div_one1"> 

     <div class="section-contents"></div> 
    </div> 
</div> 

理想的情況下,我會升用於「javascript:showMe(1)」的ike來切換「div_one1」等等。

請幫忙

+1

首先快速側面說明:把一個'div'的'了'裏面是無效的HTML,並可能導致某些瀏覽器的問題;使用'span' - 如果需要,你仍然可以設置'display:block'的形式,但不會導致問題再次出現(或者只是樣式化'a'標籤並將內部元素放在一起) –

+0

注意到並感謝你! – babusi

+0

@CollinGrady Fyi你可以在HTML5以後的錨標籤裏面有塊元素。它仍然是一個有效的HTML。 – PSL

回答

0

你寫的代碼純粹是一個show函數。您每次撥打電話showMe就隱藏它,然後再顯示。

像下面的內容可以使它的實際切換:

function showMe(num) 
{ 
    if ($('#div_one'+num).is(":visible")) 
    { // the div is visible, so we just want to hide it 
     $('#div_one'+num).hide(); 
    } 
    else 
    { // the div is not visible, so hide the rest and show it 
     $('.section').hide(0); 
     $('#div_one'+num).fadeIn(1000); 
    } 

    // I don't know what these next two lines are for, 
    // as your code sample doesn't include them, so leaving as-is :) 
    $('.height-auto').removeClass('height-auto'); 
    $('#strict').addClass('height-auto'); 
} 

然而,jQuery有一些方便的內置功能,可以使它有點短:

function showMe(num) 
{ 
    $('#div_one'+num).siblings('.section').hide(); 
    $('#div_one'+num).fadeToggle(); 

    // I don't know what these next two lines are for, 
    // as your code sample doesn't include them, so leaving as-is :) 
    $('.height-auto').removeClass('height-auto'); 
    $('#strict').addClass('height-auto'); 
} 

jsFiddle

+0

熱潮!非常簡潔,重點突出。謝謝!我會保存在我的筆記 – babusi

0

我遲到了,但爲你打造它,只是作爲回答發佈

$(document).ready(function(){ 
    $('.section').hide(); 
    $('#div_one1').show(); 
}); 

function showMe(num){ 
    $('.section').hide(); 
    $('#div_one'+num).fadeIn(300); 
} 

DEMO.

+0

謝謝。請接受我的謙虛upvote – babusi

+0

真的很感激它,謝謝:-) –

+0

這不會切換的東西;它仍然只顯示該部分,不會再隱藏它:) –