2017-08-14 70 views
-1

我對jQuery/JavaScript相當新,我想我不明白我自己的代碼。停止從重新點擊jQuery的div

它的行爲與我想要的完全相同,但是當我重新點擊.projtog時,它會重新切換我的.projContent,我不想那樣做。當我重新點擊其關聯的.projtog時,我想.projContent關閉。 我試着給.projContent一個布爾值,但並不知道如何處理它。

這裏是我的代碼:

$('div.projContent').css('height', '0vh'); 
 

 
$('h2.projtog').click(function() { 
 

 
    var $dataName_2 = $(this).data("name"); 
 

 
    $('div.projContent').css('height', '0vh'); 
 

 
    setTimeout(function() { 
 
    $("#" + $dataName_2).css('height', '100vh'); 
 
    }, 290); 
 

 
});
#projectSection { 
 
    display: -webkit-box; 
 
    display: -ms-flexbox; 
 
    display: flex; 
 
    -webkit-box-align: center; 
 
    -ms-flex-align: center; 
 
    align-items: center; 
 
    -webkit-box-orient: vertical; 
 
    -webkit-box-direction: normal; 
 
    -ms-flex-direction: column; 
 
    flex-direction: column; 
 
    padding: 1em; 
 
    padding-top: 0; 
 
    width: 45vw; 
 
    min-height: 100%; 
 
    overflow-y: scroll; 
 
    overflow-x: hidden; 
 
} 
 

 
.proj { 
 
    max-width: 40vw; 
 
    color: #003c48; 
 
    max-height: 100vh; 
 
} 
 

 
.projtog { 
 
    text-align: left; 
 
    transition: all 0.2s ease; 
 
} 
 

 
.projContent { 
 
    max-width: 40vw; 
 
    max-height: 57vh; 
 
    overflow: scroll; 
 
    transition: all ease-in-out 200ms; 
 
    position: relative; 
 
} 
 

 
.projectImages { 
 
    max-width: 40vw; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="proj"> 
 
    <h2 data-name="projectX" class="projtog"></h2> 
 
    <h3></h3> 
 
    <div class="projContent" id="projectX"> 
 
    <p></p> 
 
    <img class="projectImages" src=""> 
 
    </div> 
 
</div>

+0

但是... .projContent IS #projectX ... –

+0

哦,我想我看到了......你想連續點擊不會導致它隱藏和重新顯示。在這種情況下......你需要一些條件來測試點擊的是否是活動的。 –

+0

你可以在最後刪除'projtog'類。這樣事件就不會繼續發射。 (''click','.projtog',function(){...'並添加'$(this).removeClass(')',你必須稍微改寫一下這個事件。 projtong')' – nurdyguy

回答

3
$('div.projContent').hide(); 

$('h2.projtog').click(function() { 
    $(this).nextAll(".projContent").toggle(); 
}); 

上面的代碼將切換projContent股利。

+1

你可以通過隱藏'projContent' div來進一步改進它,通過CSS在頁面加載時像'.projContent {display:none;}' –