0

当用户在其打开状态之外单击时,我试图隐藏我的下拉菜单,我使用一个标志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();
        });
4

2 回答 2

1

创建一个条件来检查单击的内容是否在下拉列表中,如果单击的内容不在下拉列表中,则隐藏下拉列表:

$(document).on('click', function(e){
    if( isActive && $(e.target).closest('.social-share-options').length === 0 ){
        $('.social-share-options').removeClass('is-active');
        isActive = false;
    }
});
于 2013-02-19T11:55:19.263 回答
1

我尚未对其进行测试,但我认为您需要添加e.stopPropagation(),这将防止您的事件冒泡:

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

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

于 2013-02-19T11:55:53.640 回答