简体   繁体   English

在div外部单击时关闭div的jquery

[英]jquery when clicked outside the div close the div

What actually I get is given in: http://jsfiddle.net/y9uwY/7/ 我实际得到的是在: 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). 试试这个小提琴,您的body标签将永远只是主要.select_roles元素的大小,因此将.select_roles和heights设置为100%可以为您提供一个可点击的隐藏区域(这在msot浏览器中有效,可以允许更多操作) ,也可能值得添加一些填充)。 This simply sets the .select_roles to display:none; 这只是将.select_roles设置为display:none; .select_roles but starts with the class of .active to make it display:block; 但从.active类开始使其display:block; once you click outside of the area we remove the .active class. 一旦您在区域外单击,我们将删除.active类。

Fiddle: http://jsfiddle.net/y9uwY/3/ 小提琴: http : //jsfiddle.net/y9uwY/3/

try the fiddle now http://jsfiddle.net/y9uwY/9/ 现在尝试小提琴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/ 这是更正的代码http://jsfiddle.net/y9uwY/8/

For Reference and Further Reading: What is event bubbling and capturing? 供参考和进一步阅读: 什么是事件冒泡和捕获?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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