jQuery toggle hide on click elsewhere

与世无争的帅哥 提交于 2019-12-12 20:21:24

问题


This may be a very simple but never used this type of things so no idea how to do.

I am using fadeToggle to show hide div an

$('#account-toggle').click(     
function(){
    $('#account-toggle').toggleClass('account-active');
    $('.account-group').fadeToggle('fast');
});

It is working fine.. (obviously nothing complex :P ) now what I want is to hide it when user click elsewhere on the screen.

Can anyone help me to make it happen?... thanks a lot


回答1:


Try this:

$('#account-toggle').click(function(e){
    e.stopPropagation();
    $(this).toggleClass('account-active');
    $('.account-group').fadeToggle('fast');
});

$(document).click(function(){
    $('#account-toggle.account-active').removeClass('account-active');
    $('.account-group:visible').hide();
});
  • $(document).click event is triggered whenever a user click anywhere in the page.
  • It might happen that the user clicks on the account-toggle element. This will trigger both the #account-toggle & document event due to event bubbling. To stop that we have used the e.stopPropagation() function here.


来源:https://stackoverflow.com/questions/16385993/jquery-toggle-hide-on-click-elsewhere

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!