当其他显示/隐藏div按钮点击时关闭活动div

问题描述:

查看显示/隐藏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(); 
    }); 
}); 

当水龙头被点击,你可以遍历所有其他水龙头,如果主动关闭它们:

$(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