当下拉菜单打开并且用户单击文档时,尝试关闭下拉菜单

trying to close dropdown menu when dropdown menu is open and user clicks document

本文关键字:下拉菜单 文档 单击 用户      更新时间:2023-09-26

当用户在打开状态之外单击时,我试图隐藏我的下拉菜单,我使用标志isActive来确定菜单是否打开,然后我在文档上添加了一个单击事件,以在打开时隐藏菜单,并在单击时停止在菜单上传播。然而,现在当我单击下拉锚定标记时,文档单击事件被触发。有人能建议我如何解决这个问题吗?

JS-

//User profile share tooltip
        $('.btn-social-share').on('click', function(e){
            e.preventDefault();
                if( !isActive ){
                    $('.social-share-options').show();
                    isActive = true;
                } else {
                    $('.social-share-options').hide();
                    isActive = false;
                }
        });
        /* Anything that gets to the document
           will hide the dropdown */
        $(document).on('click', function(){
            if( isActive ){
                $('.social-share-options').hide();
                isActive = false;
            }
        });
        /* Clicks within the dropdown won't make
           it past the dropdown itself */
        $('.social-share-options').click(function(e){
          e.stopPropagation();
        });

设置一个条件,检查单击的内容是否在下拉列表中,然后如果单击的内容不在下拉列表内则隐藏下拉列表:

$(document).on('click', function(e){
    if( isActive && $(e.target).closest('.social-share-options').length === 0 ){
        $('.social-share-options').removeClass('is-active');
        isActive = false;
    }
});

我还没有测试过,但我认为您需要添加e.stopPropagation(),这将防止您的事件冒泡:

  $('.btn-social-share').on('click', function(e){
        e.preventDefault();
        e.stopPropagation();
        //...

http://api.jquery.com/event.stopPropagation/