简体   繁体   中英

jquery when clicked outside the div close the div

What actually I get is given in: http://jsfiddle.net/y9uwY/7/

What I want:

  1. if user click on black area then nothin should happen
  2. clicked outside the black area must be closed

try this fiddle, your body tag will only ever be the size of the main .select_roles element, so setting the widths and heights to 100% gives you a clickable area for the hide (this works in msot browsers, to allow for a little more, might be worth adding some padding as well). This simply sets the .select_roles to display:none; but starts with the class of .active to make it display:block; once you click outside of the area we remove the .active class.

Fiddle: http://jsfiddle.net/y9uwY/3/

try the fiddle now http://jsfiddle.net/y9uwY/9/

$('.select_roles').click(function (e){
    e.stopPropagation();
                 if($(this).hasClass('active')){
                 }
                 });

            $('body').click(function (){
                 if($('.select_roles').hasClass('active')){
                     $('.select_roles').removeClass('active');
                 }
            });

You have to stop the event bubbling up to body. Here is the corrected code http://jsfiddle.net/y9uwY/8/

For Reference and Further Reading: What is event bubbling and capturing?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM