2015-05-09 146 views
0

查看顯示/隱藏div下拉鍊接。我找到了我想要做的筆。我希望活動div在另一個鏈接被點擊並打開時自動關閉。目前,用戶必須先關閉活動div,然後再查看另一個活動div。我是新來的JS,所以任何幫助表示讚賞。當其他顯示/隱藏div按鈕點擊時關閉活動div

Link to codepen

$(document).ready(function() { 
    /* hide all content divs */ 
    $('.toggle-content').hide(); 

    $('.toggle-trigger').click(function() { 
    /* if the clicked item is active*/ 
    if ($('.toggle-trigger').hasClass('active')) { 
     /* hide the next content div*/ 
     $(this).next('.toggle-content').slideUp(); 
     /* and remove the active class*/ 
     $(this).toggleClass('active'); 
    } 

    /* if the cliked item is NOT active */ 
    else { 
     /* slide the content div dwon */ 
     $(this).next('.toggle-content').slideDown(); 
     /* and add the active class*/ 
     $(this).toggleClass('active'); 
    } 
    }); 
}); 

$(document).ready(function() { 

    $('div.dropdown').each(function() { 
    var $dropdown = $(this); 

    $("a.dropdown-link", $dropdown).click(function(e) { 
     e.preventDefault(); 
     $div = $("div.dropdown-container", $dropdown); 
     $div.toggle(); 
     $("div.dropdown-container").not($div).hide(); 
     return false; 
    }); 
    }); 

    $('html').click(function() { 
    $("div.dropdown-container").hide(); 
    }); 
}); 

回答

0

當水龍頭被點擊,你可以遍歷所有其他水龍頭,如果主動關閉它們:

$(document).ready(function() { 
    /* hide all content divs */ 
    $('.toggle-content').hide(); 

    $('.toggle-trigger').click(function() { 

    /* close all other taps but not current clicked tap */ 
    closeActiveTap(this); 

    /* if the clicked item is active*/ 
    if ($(this).hasClass('active')){ 
     /* hide the next content div*/ 
     $(this).next('.toggle-content').slideUp(); 
     /* and remove the active class*/ 
     $(this).toggleClass('active'); 
    } 

    /* if the cliked item is NOT active */ 
    else { 
     /* slide the content div dwon */ 

     $(this).next('.toggle-content').slideDown(); 
     /* and add the active class*/ 
     $(this).toggleClass('active'); 

    } 
    }); 

}); 

function closeActiveTap(current){ 

    $('.toggle-trigger').each(function(index,tap){ 
    if(current!==tap && $(tap).hasClass('active')){ 
     $(tap).removeClass('active'); 
     $(tap).next('.toggle-content').slideUp(); 
    } 
    }); 

} 

功能closeActiveTap需要一個PARAM 電流(當前被點擊點擊)以確保在所有其他的水龍頭上DOM操作應該被應用到但不在當前的水龍頭上,因爲當重新處理當前的水龍頭時痛苦如果 - 其他代碼塊。

希望這會有所幫助

+0

很酷。代碼起作用,您的解釋非常合理。感謝您的幫助。 – thisismyspyname

+0

歡迎您,並感謝您的讚美:) – Blauharley